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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,666 |
Bug 20666 Export JavaDoc should examine jdk compliance
|
The Export Javadoc wizard should examine the jdk1.3/jdk1.4 compliance for a project and add the appropriate javadoc switch by default to the javadoc args viewer. Result of not fixing: Javadoc users will get errors in the console complaining about all their assert statements, and then have to figure out the switches to add to correct this problem.
|
resolved fixed
|
2c506ba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-20T19:23:18Z | 2002-06-19T15:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWriter.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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 java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xml.serialize.Method;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.Serializer;
import org.apache.xml.serialize.SerializerFactory;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.util.Assert;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
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.JavaModelException;
public class JavadocWriter {
private OutputStream fOutputStream;
private IJavaProject fJavaProject;
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 project) {
Assert.isNotNull(outputStream);
fOutputStream= new BufferedOutputStream(outputStream);
fBasePath= basePath;
fJavaProject= project;
}
public void writeXML(JavadocOptionsManager store) throws IOException, CoreException {
DocumentBuilder docBuilder= null;
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
docBuilder= factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException();
}
Document document= docBuilder.newDocument();
// Create the document
Element project= document.createElement("project"); //$NON-NLS-1$
document.appendChild(project);
project.setAttribute("name", fJavaProject.getElementName()); //$NON-NLS-1$
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.fromStandard())
xmlWriteDoclet(store, document, xmlJavadocDesc);
else
xmlWriteJavadocStandardParams(store, document, xmlJavadocDesc);
// Write the document to the stream
OutputFormat format= new OutputFormat();
format.setIndenting(true);
SerializerFactory serializerFactory= SerializerFactory.getSerializerFactory(Method.XML);
Serializer serializer= serializerFactory.makeSerializer(fOutputStream, format);
serializer.asDOMSerializer().serialize(document);
}
//writes ant file, for now only worry about one project
private void xmlWriteJavadocStandardParams(JavadocOptionsManager store, Document document, Element xmlJavadocDesc) throws DOMException, CoreException {
String destination= getPathString(new Path(store.getDestination()));
xmlJavadocDesc.setAttribute(store.DESTINATION, destination);
xmlJavadocDesc.setAttribute(store.VISIBILITY, store.getAccess());
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.getDependencies();
StringTokenizer tokenizer= new StringTokenizer(hrefs, ";"); //$NON-NLS-1$
while (tokenizer.hasMoreElements()) {
String href= (String) tokenizer.nextElement();
Element links= document.createElement("link"); //$NON-NLS-1$
xmlJavadocDesc.appendChild(links);
links.setAttribute(store.HREF, href);
}
}
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);
}
IProject proj= fJavaProject.getProject();
IPath projLoc= proj.getLocation();
if (projLoc.segmentCount() <= matchingSegments && projLoc.isPrefixOf(fullPath)) {
return getRelativePath(fullPath, matchingSegments);
}
IPath workspaceLoc= proj.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(File.separatorChar);
backSegments--;
}
int segCount= fullPath.segmentCount();
for (int i= matchingSegments; i < segCount; i++) {
if (i > matchingSegments) {
res.append(File.separatorChar);
}
res.append(fullPath.segment(i));
}
return res.toString();
}
private void xmlWriteDoclet(JavadocOptionsManager store, Document document, Element xmlJavadocDesc) throws DOMException, CoreException {
//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) throws JavaModelException {
StringBuffer buf= new StringBuffer();
Iterator iter= packages.iterator();
int nAdded= 0;
while (iter.hasNext()) {
if (nAdded > 0) {
buf.append(","); //$NON-NLS-1$
}
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();
}
}
}
|
26,298 |
Bug 26298 JUnit: Can not go to inner class and view goes crazy
|
Build 20021113 1. Create new Java project 'JUnit' with JUnit in it 2. Select Run... -> JUnit 3. Select project 'JUnit' and select "All tests..." 4. Press "Run" 5. Go to the JUnit view, observe several errors/failures 6. Observe when moving the mouse over the results: first one stays selected 7. Double click on each result starting from the top ==> reached one (4th, was an inner class) which resulted in an error dialog (see attached picture) 8. Confirm the dialog 9. The input in the lower pane now changes as you hover over the (errors/failures) Nothing in the log
|
resolved fixed
|
81f337f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-20T20:14:29Z | 2002-11-14T13:20:00Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A view presenting the failed tests in a table.
*/
class FailureRunView implements ITestRunView, IMenuListener {
private Table fTable;
private TestRunnerViewPart fRunnerViewPart;
private boolean fPressed= false;
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fFailureTabIcon= TestRunnerViewPart.createImage("obj16/failures.gif"); //$NON-NLS-1$
public FailureRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fRunnerViewPart= runner;
CTabItem failureTab= new CTabItem(tabFolder, SWT.NONE);
failureTab.setText(getName());
failureTab.setImage(fFailureTabIcon);
Composite composite= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
composite.setLayout(gridLayout);
GridData gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
composite.setLayoutData(gridData);
fTable= new Table(composite, SWT.NONE);
gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
fTable.setLayout(gridLayout);
gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTable.setLayoutData(gridData);
failureTab.setControl(composite);
failureTab.setToolTipText(JUnitMessages.getString("FailureRunView.tab.tooltip")); //$NON-NLS-1$
initMenu();
addListeners();
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fFailureTabIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTable);
fTable.setMenu(menu);
}
public String getName() {
return JUnitMessages.getString("FailureRunView.tab.title"); //$NON-NLS-1$
}
public String getTestName() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return fTable.getItem(index).getText();
}
private String getClassName() {
return cutFromTo(getSelectedText(), '(', ')');
}
private String getMethodName() {
return cutTo(getSelectedText(), '(');
}
private static String cutFromTo(String string, char from, char to){
String modified= string;
modified= modified.substring(modified.indexOf(from) + 1);
return cutTo(modified, to);
}
private static String cutTo(String string, char to){
int toIndex= string.indexOf(to);
if (toIndex == -1)
return string;
else
return string.substring(0, toIndex);
}
public void menuAboutToShow(IMenuManager manager){
if (fTable.getSelectionCount() > 0) {
String className= getClassName();
String methodName= getMethodName();
if (className != null) {
manager.add(new OpenTestAction(fRunnerViewPart, className, methodName));
manager.add(new RerunAction(fRunnerViewPart, className, methodName));
}
}
}
private String getSelectedText() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return fTable.getItem(index).getText();
}
public void setSelectedTest(String testName){
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
TableItem tableItem= items[i];
if (tableItem.getText().equals(testName)){
fTable.setSelection(new TableItem[] { tableItem });
fTable.showItem(tableItem);
return;
}
}
}
public void setFocus() {
fTable.setFocus();
}
public void endTest(String testName){
TestRunInfo testInfo= fRunnerViewPart.getTestInfo(testName);
if(testInfo == null || testInfo.fStatus == ITestRunListener.STATUS_OK)
return;
TableItem tableItem= new TableItem(fTable, SWT.NONE);
updateTableItem(testInfo, tableItem);
fTable.showItem(tableItem);
}
private void updateTableItem(TestRunInfo testInfo, TableItem tableItem) {
tableItem.setText(testInfo.fTestName);
if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE)
tableItem.setImage(fFailureIcon);
else
tableItem.setImage(fErrorIcon);
tableItem.setData(testInfo);
}
private TableItem findItemByTest(String testName) {
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
if (items[i].getText().equals(testName))
return items[i];
}
return null;
}
public void activate() {
testSelected();
}
public void aboutToStart() {
fTable.removeAll();
}
protected void testSelected() {
fRunnerViewPart.handleTestSelected(getTestName());
}
protected void addListeners() {
fTable.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTable.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTable.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e){
handleDoubleClick(e);
}
public void mouseDown(MouseEvent e) {
fPressed= true;
activate();
}
public void mouseUp(MouseEvent e) {
fPressed= false;
activate();
}
});
fTable.addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(MouseEvent e) {
TableItem tableItem= ((Table) e.getSource()).getItem(new Point(e.x, e.y));
if (fPressed & (null != tableItem)) {
fTable.setSelection(new TableItem[] { tableItem });
activate();
}
// scrolling up and down
if ((e.y + 1 > fTable.getBounds().height)
& fPressed
& (fTable.getSelectionIndex() != fTable.getItemCount() - 1)) {
fTable.setTopIndex(fTable.getTopIndex() + 1);
fTable.setSelection(fTable.getSelectionIndex() + 1);
activate();
}
if ((e.y - 1 < 0) & fPressed & (fTable.getTopIndex() != 0)) {
fTable.setTopIndex(fTable.getTopIndex() - 1);
fTable.setSelection(fTable.getSelectionIndex() - 1);
activate();
}
}
});
}
public void handleDoubleClick(MouseEvent e) {
if (fTable.getSelectionCount() > 0)
new OpenTestAction(fRunnerViewPart, getClassName(), getMethodName()).run();
}
public void newTreeEntry(String treeEntry) {
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo)
*/
public void testStatusChanged(TestRunInfo info) {
TableItem item= findItemByTest(info.fTestName);
if (item != null) {
if (info.fStatus == ITestRunListener.STATUS_OK) {
item.dispose();
return;
}
updateTableItem(info, item);
}
if (item == null && info.fStatus != ITestRunListener.STATUS_OK) {
item= new TableItem(fTable, SWT.NONE);
updateTableItem(info, item);
}
if (item != null)
fTable.showItem(item);
}
}
|
26,298 |
Bug 26298 JUnit: Can not go to inner class and view goes crazy
|
Build 20021113 1. Create new Java project 'JUnit' with JUnit in it 2. Select Run... -> JUnit 3. Select project 'JUnit' and select "All tests..." 4. Press "Run" 5. Go to the JUnit view, observe several errors/failures 6. Observe when moving the mouse over the results: first one stays selected 7. Double click on each result starting from the top ==> reached one (4th, was an inner class) which resulted in an error dialog (see attached picture) 8. Confirm the dialog 9. The input in the lower pane now changes as you hover over the (errors/failures) Nothing in the log
|
resolved fixed
|
81f337f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-20T20:14:29Z | 2002-11-14T13:20:00Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/HierarchyRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jdt.junit.ITestRunListener;
/*
* A view that shows the contents of a test suite
* as a tree.
*/
class HierarchyRunView implements ITestRunView, IMenuListener {
/**
* The tree widget
*/
private Tree fTree;
public static final int IS_SUITE= -1;
/**
* Helper used to resurrect test hierarchy
*/
private static class SuiteInfo {
public int fTestCount;
public TreeItem fTreeItem;
public SuiteInfo(TreeItem treeItem, int testCount){
fTreeItem= treeItem;
fTestCount= testCount;
}
}
/**
* Vector of SuiteInfo items
*/
private Vector fSuiteInfos= new Vector();
/**
* Maps test names to TreeItems.
* If there is one treeItem for a test then the
* value of the map corresponds to the item, otherwise
* there is a list of tree items.
*/
private Map fTreeItemMap= new HashMap();
private TestRunnerViewPart fTestRunnerPart;
private boolean fPressed= false;
private final Image fOkIcon= TestRunnerViewPart.createImage("obj16/testok.gif"); //$NON-NLS-1$
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fHierarchyIcon= TestRunnerViewPart.createImage("obj16/testhier.gif"); //$NON-NLS-1$
private final Image fSuiteIcon= TestRunnerViewPart.createImage("obj16/tsuite.gif"); //$NON-NLS-1$
private final Image fSuiteErrorIcon= TestRunnerViewPart.createImage("obj16/tsuiteerror.gif"); //$NON-NLS-1$
private final Image fSuiteFailIcon= TestRunnerViewPart.createImage("obj16/tsuitefail.gif"); //$NON-NLS-1$
private final Image fTestIcon= TestRunnerViewPart.createImage("obj16/test.gif"); //$NON-NLS-1$
public HierarchyRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fTestRunnerPart= runner;
CTabItem hierarchyTab= new CTabItem(tabFolder, SWT.NONE);
hierarchyTab.setText(getName());
hierarchyTab.setImage(fHierarchyIcon);
Composite testTreePanel= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
testTreePanel.setLayout(gridLayout);
GridData gridData= new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
testTreePanel.setLayoutData(gridData);
hierarchyTab.setControl(testTreePanel);
hierarchyTab.setToolTipText(JUnitMessages.getString("HierarchyRunView.tab.tooltip")); //$NON-NLS-1$
fTree= new Tree(testTreePanel, SWT.V_SCROLL);
gridData= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTree.setLayoutData(gridData);
initMenu();
addListeners();
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fOkIcon.dispose();
fHierarchyIcon.dispose();
fTestIcon.dispose();
fSuiteIcon.dispose();
fSuiteErrorIcon.dispose();
fSuiteFailIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTree);
fTree.setMenu(menu);
}
private String getTestLabel() {
TreeItem treeItem= fTree.getSelection()[0];
if(treeItem == null)
return ""; //$NON-NLS-1$
return treeItem.getText();
}
private TestRunInfo getTestInfo() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length == 0)
return null;
return ((TestRunInfo)treeItems[0].getData());
}
public String getClassName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return extractClassName(testInfo.fTestName);
}
public String getTestName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return testInfo.fTestName;
}
private String extractClassName(String testNameString) {
if (testNameString == null)
return null;
int index= testNameString.indexOf('(');
if (index < 0)
return testNameString;
testNameString= testNameString.substring(index + 1);
return testNameString.substring(0, testNameString.indexOf(')'));
}
public String getName() {
return JUnitMessages.getString("HierarchyRunView.tab.title"); //$NON-NLS-1$
}
public void setSelectedTest(String testName) {
TreeItem treeItem= findFirstItem(testName);
if (treeItem != null)
fTree.setSelection(new TreeItem[]{treeItem});
}
public void endTest(String testName) {
TreeItem treeItem= findFirstNotRunItem(testName);
// workaround for bug 8657
if (treeItem == null)
return;
TestRunInfo testInfo= fTestRunnerPart.getTestInfo(testName);
updateItem(treeItem, testInfo);
if (testInfo.fTrace != null)
fTree.showItem(treeItem);
}
private void updateItem(TreeItem treeItem, TestRunInfo testInfo) {
treeItem.setData(testInfo);
if(testInfo.fStatus == ITestRunListener.STATUS_OK) {
treeItem.setImage(fOkIcon);
return;
}
if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE)
treeItem.setImage(fFailureIcon);
else if (testInfo.fStatus == ITestRunListener.STATUS_ERROR)
treeItem.setImage(fErrorIcon);
propagateStatus(treeItem, testInfo.fStatus);
}
void propagateStatus(TreeItem item, int status) {
TreeItem parent= item.getParentItem();
if (parent == null)
return;
Image parentImage= parent.getImage();
if (status == ITestRunListener.STATUS_FAILURE) {
if (parentImage == fSuiteErrorIcon || parentImage == fSuiteFailIcon)
return;
parent.setImage(fSuiteFailIcon);
} else {
if (parentImage == fSuiteErrorIcon)
return;
parent.setImage(fSuiteErrorIcon);
}
propagateStatus(parent, status);
}
public void activate() {
testSelected();
}
public void setFocus() {
fTree.setFocus();
}
public void aboutToStart() {
fTree.removeAll();
fSuiteInfos.removeAllElements();
fTreeItemMap= new HashMap();
}
protected void testSelected() {
fTestRunnerPart.handleTestSelected(getTestName());
}
public void menuAboutToShow(IMenuManager manager) {
if (fTree.getSelectionCount() > 0) {
final TreeItem treeItem= fTree.getSelection()[0];
TestRunInfo testInfo= (TestRunInfo) treeItem.getData();
if (testInfo.fStatus == IS_SUITE) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
manager.add(new OpenTestAction(fTestRunnerPart, className));
} else {
manager.add(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel()));
manager.add(new RerunAction(fTestRunnerPart, getClassName(), getTestLabel()));
}
}
}
private void addListeners() {
fTree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTree.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTree.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
handleDoubleClick(e);
}
public void mouseDown(MouseEvent e) {
fPressed= true;
}
public void mouseUp(MouseEvent e) {
fPressed= false;
}
});
fTree.addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(MouseEvent e) {
if (!(e.getSource() instanceof Tree))
return;
TreeItem[] treeItem= {((Tree) e.getSource()).getItem(new Point(e.x, e.y))};
if (fPressed & (null != treeItem[0])) {
fTree.setSelection(treeItem);
activate();
}
// scroll
if ((e.y < 1) & fPressed) {
try {
TreeItem tItem= treeItem[0].getParentItem();
fTree.setSelection(new TreeItem[] { tItem });
activate();
} catch (Exception ex) {
}
}
}
});
}
void handleDoubleClick(MouseEvent e) {
TestRunInfo testInfo= getTestInfo();
if(testInfo == null)
return;
if ((testInfo.fStatus == IS_SUITE)) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
(new OpenTestAction(fTestRunnerPart, className)).run();
}
else {
(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel())).run();
}
}
public void newTreeEntry(String treeEntry) {
int index0= treeEntry.indexOf(',');
int index1= treeEntry.lastIndexOf(',');
String label= treeEntry.substring(0, index0).trim();
TestRunInfo testInfo= new TestRunInfo(label);
//fTestInfo.addElement(testInfo);
int index2;
if((index2= label.indexOf('(')) > 0)
label= label.substring(0, index2);
if((index2= label.indexOf('@')) > 0)
label= label.substring(0, index2);
String isSuite= treeEntry.substring(index0+1, index1);
int testCount= Integer.parseInt(treeEntry.substring(index1+1));
TreeItem treeItem;
while((fSuiteInfos.size() > 0) && (((SuiteInfo) fSuiteInfos.lastElement()).fTestCount == 0)) {
fSuiteInfos.removeElementAt(fSuiteInfos.size()-1);
}
if(fSuiteInfos.size() == 0){
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(fTree, SWT.NONE);
treeItem.setImage(fSuiteIcon);
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else if(isSuite.equals("true")) { //$NON-NLS-1$
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fHierarchyIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else {
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fTestIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
mapTest(testInfo, treeItem);
}
treeItem.setText(label);
treeItem.setData(testInfo);
}
private void mapTest(TestRunInfo info, TreeItem item) {
String test= info.fTestName;
Object o= fTreeItemMap.get(test);
if (o == null) {
fTreeItemMap.put(test, item);
return;
}
if (o instanceof TreeItem) {
List list= new ArrayList();
list.add(o);
list.add(item);
fTreeItemMap.put(test, list);
return;
}
if (o instanceof List) {
((List)o).add(item);
}
}
private TreeItem findFirstNotRunItem(String testName) {
Object o= fTreeItemMap.get(testName);
if (o instanceof TreeItem)
return (TreeItem)o;
if (o instanceof List) {
List l= (List)o;
for (int i= 0; i < l.size(); i++) {
TreeItem item= (TreeItem)l.get(i);
if (item.getImage() == fTestIcon)
return item;
}
return null;
}
return null;
}
private TreeItem findFirstItem(String testName) {
Object o= fTreeItemMap.get(testName);
if (o instanceof TreeItem)
return (TreeItem)o;
if (o instanceof List) {
return (TreeItem)((List)o).get(0);
}
return null;
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo, int)
*/
public void testStatusChanged(TestRunInfo newInfo) {
Object o= fTreeItemMap.get(newInfo.fTestName);
if (o instanceof TreeItem) {
updateItem((TreeItem)o, newInfo);
return;
}
if (o instanceof List) {
List l= (List)o;
for (int i= 0; i < l.size(); i++)
updateItem((TreeItem)l.get(i), newInfo);
}
}
}
|
32,414 |
Bug 32414 Outline inconsistent with source, and showing blank entries
|
build I20030220 After doing some edits to a file, the outline had some blank entries at the end. Also, clicking on the some of the remaining items jumped to the wrong place in the source. See attached screen shot. Edits I was doing included pasting methods in from another CU and deleting methods in the text (all in text editor, not outline).
|
resolved fixed
|
142fd4f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-21T15:09:49Z | 2003-02-20T22:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.jface.text.Assert;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
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.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.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.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.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.model.WorkbenchAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
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.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
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.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 {
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(false);
return;
}
}
IJavaElementDelta delta= findElement(base, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) {
if (delta == null || unit == null)
return null;
IJavaElement element= delta.getElement();
if (unit.equals(element))
return delta;
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;
public JavaOutlineViewer(Tree tree) {
super(tree);
setAutoExpandLevel(ALL_LEVELS);
}
/**
* Investigates the given element change event and if affected incrementally
* updates the outline.
*/
public void reconcile(IJavaElementDelta delta) {
fReorderedMembers= false;
if (getSorter() == null) {
if (fTopLevelTypeOnly
&& delta.getElement() instanceof IType
&& (delta.getKind() & IJavaElementDelta.ADDED) != 0)
{
refresh(false);
} else {
Widget w= findItem(fInput);
if (w != null && !w.isDisposed())
update(w, delta);
if (fReorderedMembers) {
refresh(false);
fReorderedMembers= false;
}
}
} else {
// just for now
refresh(false);
}
}
/*
* @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;
}
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 IMember && !(element instanceof IInitializer))
return ((IMember) element).getNameRange();
if (element instanceof ISourceReference)
return ((ISourceReference) element).getSourceRange();
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;
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) {
// 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);
if (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, (Object) e);
} else {
// nothing to reuse
createTreeItem(w, (Object) 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());
}
/*
* @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;
if (cu.isWorkingCopy()) {
return cu.getOriginalElement().getResource();
} else {
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();
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, "class_obj.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$
}
};
/** 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 Hashtable fActions= new Hashtable();
private TogglePresentationAction fTogglePresentation;
private GotoErrorAction fPreviousError;
private GotoErrorAction fNextError;
private TextEditorAction fShowJavadoc;
private TextOperationAction fUndo;
private TextOperationAction fRedo;
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();
fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$
fPreviousError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR);
fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$
fNextError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR);
fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$
fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO);
fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO);
fTogglePresentation.setEditor(editor);
fPreviousError.setEditor(editor);
fNextError.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) {
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.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 (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fOutlineViewer.refresh(false);
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addPostSelectionChangedListener(listener);
else
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removePostSelectionChangedListener(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();
}
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);
}
}
/*
* @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);
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.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
contextMenuAboutToShow(manager);
}
});
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 RefactorActionGroup(this),
new GenerateActionGroup(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, fPreviousError);
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError);
bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc);
bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError);
bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError);
fActionGroups.fillActionBars(bars);
IStatusLineManager statusLineManager= site.getActionBars().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);
}
});
initDragAndDrop();
}
public void dispose() {
if (fEditor == null)
return;
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
fEditor.outlinePageClosed();
fEditor= null;
fSelectionChangedListeners.clear();
fSelectionChangedListeners= 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);
fPreviousError.setEditor(null);
fNextError.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.getElementType() == IJavaElement.TYPE) {
IJavaElement parent= element.getParent();
int type= parent.getElementType();
return (type != IJavaElement.COMPILATION_UNIT && type != 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
Control control= fOutlineViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fOutlineViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
}
|
32,384 |
Bug 32384 Cannot open type hierarchy after a cancel
|
JUnit setup 1) open the type hierarchy on TestCase 2) press F4 on Object 3) cancel in progress bar 4) press F4 on Object again ->nothing happens
|
resolved fixed
|
6abf625
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-21T19:11:42Z | 2003-02-20T19:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyLifeCycle.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
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.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IRegion;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.ITypeHierarchyChangedListener;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Manages a type hierarchy, to keep it refreshed, and to allow it to be shared.
*/
public class TypeHierarchyLifeCycle implements ITypeHierarchyChangedListener, IElementChangedListener {
private boolean fHierarchyRefreshNeeded;
private ITypeHierarchy fHierarchy;
private IJavaElement fInputElement;
private boolean fIsSuperTypesOnly;
private boolean fReconciled;
private List fChangeListeners;
public TypeHierarchyLifeCycle() {
this(false);
}
public TypeHierarchyLifeCycle(boolean isSuperTypesOnly) {
fHierarchy= null;
fInputElement= null;
fIsSuperTypesOnly= isSuperTypesOnly;
fChangeListeners= new ArrayList(2);
fReconciled= false;
}
public ITypeHierarchy getHierarchy() {
return fHierarchy;
}
public IJavaElement getInputElement() {
return fInputElement;
}
public void freeHierarchy() {
if (fHierarchy != null) {
fHierarchy.removeTypeHierarchyChangedListener(this);
JavaCore.removeElementChangedListener(this);
fHierarchy= null;
fInputElement= null;
}
}
public void removeChangedListener(ITypeHierarchyLifeCycleListener listener) {
fChangeListeners.remove(listener);
}
public void addChangedListener(ITypeHierarchyLifeCycleListener listener) {
if (!fChangeListeners.contains(listener)) {
fChangeListeners.add(listener);
}
}
private void fireChange(IType[] changedTypes) {
for (int i= fChangeListeners.size()-1; i>=0; i--) {
ITypeHierarchyLifeCycleListener curr= (ITypeHierarchyLifeCycleListener) fChangeListeners.get(i);
curr.typeHierarchyChanged(this, changedTypes);
}
}
public void ensureRefreshedTypeHierarchy(final IJavaElement element, IRunnableContext context) throws JavaModelException {
if (element == null || !element.exists()) {
freeHierarchy();
return;
}
boolean hierachyCreationNeeded= (fHierarchy == null || !element.equals(fInputElement));
if (hierachyCreationNeeded || fHierarchyRefreshNeeded) {
IRunnableWithProgress op= new IRunnableWithProgress() {
public void run(IProgressMonitor pm) throws InvocationTargetException {
try {
doHierarchyRefresh(element, pm);
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
} finally {
if (pm != null) {
pm.done();
}
}
}
};
try {
context.run(true, true, op);
} catch (InvocationTargetException e) {
Throwable th= e.getTargetException();
if (th instanceof JavaModelException) {
throw (JavaModelException)th;
} else {
throw new JavaModelException(th, IStatus.ERROR);
}
} catch (InterruptedException e) {
// Not cancelable.
}
fHierarchyRefreshNeeded= false;
}
}
private void doHierarchyRefresh(IJavaElement element, IProgressMonitor pm) throws JavaModelException {
boolean hierachyCreationNeeded= (fHierarchy == null || !element.equals(fInputElement));
// to ensore the order of the two listeners always remove / add listeners on operations
// on type hierarchies
if (fHierarchy != null) {
fHierarchy.removeTypeHierarchyChangedListener(this);
JavaCore.removeElementChangedListener(this);
}
if (hierachyCreationNeeded) {
fInputElement= element;
if (element.getElementType() == IJavaElement.TYPE) {
IType type= (IType) element;
if (fIsSuperTypesOnly) {
fHierarchy= type.newSupertypeHierarchy(pm);
} else {
fHierarchy= type.newTypeHierarchy(pm);
}
} else {
IRegion region= JavaCore.newRegion();
if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
// for projects only add the contained source folders
IPackageFragmentRoot[] roots= ((IJavaProject) element).getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (!roots[i].isExternal()) {
region.add(roots[i]);
}
}
} else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
IPackageFragmentRoot[] roots= element.getJavaProject().getPackageFragmentRoots();
String name= element.getElementName();
for (int i= 0; i < roots.length; i++) {
IPackageFragment pack= roots[i].getPackageFragment(name);
if (pack.exists()) {
region.add(pack);
}
}
} else {
region.add(element);
}
IJavaProject jproject= element.getJavaProject();
fHierarchy= jproject.newTypeHierarchy(region, pm);
}
} else {
fHierarchy.refresh(pm);
}
fHierarchy.addTypeHierarchyChangedListener(this);
JavaCore.addElementChangedListener(this);
}
/*
* @see ITypeHierarchyChangedListener#typeHierarchyChanged
*/
public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) {
fHierarchyRefreshNeeded= true;
}
/*
* @see IElementChangedListener#elementChanged(ElementChangedEvent)
*/
public void elementChanged(ElementChangedEvent event) {
if (fChangeListeners.isEmpty()) {
return;
}
IJavaElement elem= event.getDelta().getElement();
if (!isReconciled() && elem instanceof IWorkingCopy && ((IWorkingCopy)elem).isWorkingCopy()) {
return;
}
if (fHierarchyRefreshNeeded) {
fireChange(null);
} else {
ArrayList changedTypes= new ArrayList();
processDelta(event.getDelta(), changedTypes);
if (changedTypes.size() > 0) {
fireChange((IType[]) changedTypes.toArray(new IType[changedTypes.size()]));
}
}
}
/*
* Assume that the hierarchy is intact (no refresh needed)
*/
private void processDelta(IJavaElementDelta delta, ArrayList changedTypes) {
IJavaElement element= delta.getElement();
switch (element.getElementType()) {
case IJavaElement.TYPE:
processTypeDelta((IType) element, changedTypes);
processChildrenDelta(delta, changedTypes); // (inner types)
break;
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
processChildrenDelta(delta, changedTypes);
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit cu= (ICompilationUnit)element;
boolean isWorkingCopyRemove= isWorkingCopyRemove(cu, delta.getKind());
if (isWorkingCopyRemove || delta.getKind() == IJavaElementDelta.CHANGED && isPossibleStructuralChange(delta.getFlags())) {
try {
if (isWorkingCopyRemove)
cu= (ICompilationUnit)cu.getOriginalElement();
if (cu.exists()) {
IType[] types= cu.getAllTypes();
for (int i= 0; i < types.length; i++) {
processTypeDelta(types[i], changedTypes);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else {
processChildrenDelta(delta, changedTypes);
}
break;
case IJavaElement.CLASS_FILE:
if (delta.getKind() == IJavaElementDelta.CHANGED) {
try {
IType type= ((IClassFile) element).getType();
processTypeDelta(type, changedTypes);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else {
processChildrenDelta(delta, changedTypes);
}
break;
}
}
private boolean isPossibleStructuralChange(int flags) {
return (flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT;
}
private boolean isWorkingCopyRemove(ICompilationUnit cu, int deltaKind) {
return isReconciled() && deltaKind == IJavaElementDelta.REMOVED && cu.isWorkingCopy();
}
private void processTypeDelta(IType type, ArrayList changedTypes) {
type= (IType) JavaModelUtil.toOriginal(type);
if (getHierarchy().contains(type)) {
changedTypes.add(type);
}
}
private void processChildrenDelta(IJavaElementDelta delta, ArrayList changedTypes) {
IJavaElementDelta[] children= delta.getAffectedChildren();
for (int i= 0; i < children.length; i++) {
processDelta(children[i], changedTypes); // recursive
}
}
public boolean isReconciled() {
return fReconciled;
}
public void setReconciled(boolean reconciled) {
fReconciled= reconciled;
}
}
|
32,384 |
Bug 32384 Cannot open type hierarchy after a cancel
|
JUnit setup 1) open the type hierarchy on TestCase 2) press F4 on Object 3) cancel in progress bar 4) press F4 on Object again ->nothing happens
|
resolved fixed
|
6abf625
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-21T19:11:42Z | 2003-02-20T19:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
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.DragSource;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.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.PartInitException;
import org.eclipse.ui.actions.ActionContext;
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.JavaModelUtil;
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.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.viewsupport.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;
/**
* 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 fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
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;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fHierarchyLifeCycle.setReconciled(isReconciled);
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) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* 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) {
if (member.getElementType() != IJavaElement.TYPE) {
// methods are working copies
if (fHierarchyLifeCycle.isReconciled()) {
member= JavaModelUtil.toWorkingCopy(member);
}
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();
}
// types are originals
member= JavaModelUtil.toOriginal(member);
if (!member.equals(fSelectedType)) {
getCurrentViewer().setSelection(new StructuredSelection(member), 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();
}
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(element);
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();
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow());
} catch (JavaModelException e) {
JavaPlugin.log(e);
clearInput();
return;
}
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer(true);
}
IType root= getSelectableType(fInputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
fPagebook.showPage(fTypeMethodsSplitter);
}
}
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();
fMethodsViewer.dispose();
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.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) {
updateHierarchyViewer(false);
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
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.addSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
}
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.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
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){
Control control= viewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// 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$
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 < fToggleOrientationActions.length; i++) {
viewMenu.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);
IJavaElement input= 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 RefactorActionGroup(this),
new GenerateActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
initDragAndDrop();
}
/**
* 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.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(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());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
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) {
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) {
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 pagae
// 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(false);
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;
}
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
}
});
}
}
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 (JavaModelException e) {
JavaPlugin.log(e);
clearInput();
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer(false);
} else {
// elements in hierarchy modified
fMethodsViewer.refresh();
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 } );
}
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) input;
if (elem instanceof IMember) {
return elem;
} else {
int kind= elem.getElementType();
if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) {
return elem;
}
}
}
return null;
}
/*
* @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());
}
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;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
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) {
doTypeHierarchyChanged(fHierarchyLifeCycle, 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);
}
}
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit.core/src/org/eclipse/jdt/junit/ITestRunListener.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.junit;
/**
* A listener interface for observing the execution of a test run.
* <p>
* Clients contributing to the org.eclipse.jdt.junit.testRunListener
* extension point implement this interface.
*
* @since 2.1
*/
public interface ITestRunListener {
/**
* Test passed.
*
* @see ITestRunListener#testFailed
*/
public static final int STATUS_OK= 0;
/**
* Test had an error an unanticipated exception occurred.
*
* @see ITestRunListener#testFailed
*/
public static final int STATUS_ERROR= 1;
/**
* Test had a failure an assertion failed.
*
* @see ITestRunListener#testFailed
*/
public static final int STATUS_FAILURE= 2;
/**
* A test run has started.
*
* @param testCount the number of tests that will be run.
*/
public void testRunStarted(int testCount);
/**
* A test run ended.
*
* @param elapsedTime the elapsed time of the test run.
*/
public void testRunEnded(long elapsedTime);
/**
* A test run was stopped before it ended.
*/
public void testRunStopped(long elapsedTime);
/**
* A test started.
*
* @param elapsedTime the elapsed time of the test until it got stopped.
*/
public void testStarted(String testName);
/**
* A test ended.
*
* @param testName the name of the test that has started
*/
public void testEnded(String testName);
/**
* A test failed.
*
* @param testName the name of the test that has ended.
* @param status the status of the test.
* @param trace the stack trace in the case of a failure.
*/
public void testFailed(int status, String testName, String trace);
/**
* The test runner VM has terminated.
*
*/
public void testRunTerminated();
/**
* A single test was reran.
* @param testClass the name of the test class.
* @param testName the name of the test.
* @param status the status of the run
* @param trace the stack trace in the case of a failure.
*/
public void testReran(String testClass, String testName, int status, String trace);
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitMainTab.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Sebastian Davids: [email protected]
******************************************************************************/
package org.eclipse.jdt.internal.junit.launcher;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
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.IPackageFragmentRoot;
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.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
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.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
/**
* This tab appears in the LaunchConfigurationDialog for launch configurations that
* require Java-specific launching information such as a main type and JRE.
*/
public class JUnitMainTab extends JUnitLaunchConfigurationTab {
// Project UI widgets
private Label fProjLabel;
private Text fProjText;
private Button fProjButton;
private Button fKeepRunning;
// Test class UI widgets
private Text fTestText;
private Button fSearchButton;
private final Image fTestIcon= createImage("obj16/test.gif"); //$NON-NLS-1$
private Label fTestMethodLabel;
private Text fContainerText;
private IJavaElement fContainerElement;
private final ILabelProvider fJavaElementLabelProvider= new JavaElementLabelProvider();
private Button fContainerSearchButton;
private Button fTestContainerRadioButton;
private Button fTestRadioButton;
/**
* @see ILaunchConfigurationTab#createControl(TabItem)
*/
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
GridLayout topLayout = new GridLayout();
topLayout.numColumns= 2;
comp.setLayout(topLayout);
new Label(comp, SWT.NONE);
createProjectGroup(comp);
createTestSelectionGroup(comp);
createTestContainerSelectionGroup(comp);
createKeepAliveGroup(comp);
}
private void createTestContainerSelectionGroup(Composite comp) {
GridData gd;
fTestContainerRadioButton= new Button(comp, SWT.RADIO);
fTestContainerRadioButton.setText(JUnitMessages.getString("JUnitMainTab.label.container")); //$NON-NLS-1$
gd = new GridData();
gd.horizontalSpan = 2;
fTestContainerRadioButton.setLayoutData(gd);
fTestContainerRadioButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (fTestContainerRadioButton.getSelection())
testModeChanged();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
fContainerText = new Text(comp, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= 20;
fContainerText.setLayoutData(gd);
fContainerText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent evt) {
updateLaunchConfigurationDialog();
}
});
fContainerSearchButton = new Button(comp, SWT.PUSH);
fContainerSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$
fContainerSearchButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleContainerSearchButtonSelected();
}
});
setButtonGridData(fContainerSearchButton);
}
private void handleContainerSearchButtonSelected() {
IJavaElement javaElement= chooseContainer(fContainerElement);
if (javaElement != null) {
fContainerElement= javaElement;
fContainerText.setText(getPresentationName(javaElement));
}
}
public void createKeepAliveGroup(Composite comp) {
GridData gd;
fKeepRunning = new Button(comp, SWT.CHECK);
fKeepRunning.setText(JUnitMessages.getString("JUnitMainTab.label.keeprunning")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalSpan= 2;
fKeepRunning.setLayoutData(gd);
}
public void createTestSelectionGroup(Composite comp) {
GridData gd;
fTestRadioButton= new Button(comp, SWT.RADIO /*| SWT.LEFT*/);
fTestRadioButton.setText(JUnitMessages.getString("JUnitMainTab.label.test")); //$NON-NLS-1$
gd = new GridData();
gd.horizontalSpan = 2;
fTestRadioButton.setLayoutData(gd);
fTestRadioButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (fTestRadioButton.getSelection())
testModeChanged();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
fTestText = new Text(comp, SWT.SINGLE | SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= 20;
fTestText.setLayoutData(gd);
fTestText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent evt) {
updateLaunchConfigurationDialog();
}
});
fSearchButton = new Button(comp, SWT.PUSH);
fSearchButton.setEnabled(fProjText.getText().length() > 0);
fSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$
fSearchButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleSearchButtonSelected();
}
});
setButtonGridData(fSearchButton);
fTestMethodLabel= new Label(comp, SWT.NONE);
fTestMethodLabel.setText(""); //$NON-NLS-1$
gd= new GridData();
gd.horizontalSpan = 2;
gd.horizontalIndent= 20;
fTestMethodLabel.setLayoutData(gd);
}
public void createProjectGroup(Composite comp) {
GridData gd;
fProjLabel = new Label(comp, SWT.NONE);
fProjLabel.setText(JUnitMessages.getString("JUnitMainTab.label.project")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalSpan = 2;
fProjLabel.setLayoutData(gd);
fProjText= new Text(comp, SWT.SINGLE | SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
fProjText.setLayoutData(gd);
fProjText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent evt) {
updateLaunchConfigurationDialog();
boolean isSingleTestMode= fTestRadioButton.getSelection();
fSearchButton.setEnabled(isSingleTestMode && fProjText.getText().length() > 0);
}
});
fProjButton = new Button(comp, SWT.PUSH);
fProjButton.setText(JUnitMessages.getString("JUnitMainTab.label.browse")); //$NON-NLS-1$
fProjButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleProjectButtonSelected();
}
});
setButtonGridData(fProjButton);
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
/**
* @see ILaunchConfigurationTab#initializeFrom(ILaunchConfiguration)
*/
public void initializeFrom(ILaunchConfiguration config) {
updateProjectFromConfig(config);
String containerHandle= ""; //$NON-NLS-1$
try {
containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
} catch (CoreException ce) {
}
if (containerHandle.length() > 0)
updateTestContainerFromConfig(config);
else
updateTestTypeFromConfig(config);
updateKeepRunning(config);
}
private void updateKeepRunning(ILaunchConfiguration config) {
boolean running= false;
try {
running= config.getAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, false);
} catch (CoreException ce) {
}
fKeepRunning.setSelection(running);
}
protected void updateProjectFromConfig(ILaunchConfiguration config) {
String projectName= ""; //$NON-NLS-1$
try {
projectName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
} catch (CoreException ce) {
}
fProjText.setText(projectName);
}
protected void updateTestTypeFromConfig(ILaunchConfiguration config) {
String testTypeName= ""; //$NON-NLS-1$
String testMethodName= ""; //$NON-NLS-1$
try {
testTypeName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$
testMethodName = config.getAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, ""); //$NON-NLS-1$
} catch (CoreException ce) {
}
fTestRadioButton.setSelection(true);
setEnableSingleTestGroup(true);
setEnableContainerTestGroup(false);
fTestContainerRadioButton.setSelection(false);
fTestText.setText(testTypeName);
fContainerText.setText(""); //$NON-NLS-1$
if (!"".equals(testMethodName)) { //$NON-NLS-1$
fTestMethodLabel.setText(JUnitMessages.getString("JUnitMainTab.label.method")+testMethodName); //$NON-NLS-1$
} else {
fTestMethodLabel.setText(""); //$NON-NLS-1$
}
}
protected void updateTestContainerFromConfig(ILaunchConfiguration config) {
String containerHandle= ""; //$NON-NLS-1$
try {
containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
if (containerHandle.length() > 0) {
fContainerElement= JavaCore.create(containerHandle);
}
} catch (CoreException ce) {
}
fTestContainerRadioButton.setSelection(true);
setEnableSingleTestGroup(false);
setEnableContainerTestGroup(true);
fTestRadioButton.setSelection(false);
if (fContainerElement != null)
fContainerText.setText(getPresentationName(fContainerElement));
fTestText.setText(""); //$NON-NLS-1$
}
/**
* @see ILaunchConfigurationTab#performApply(ILaunchConfigurationWorkingCopy)
*/
public void performApply(ILaunchConfigurationWorkingCopy config) {
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)fProjText.getText());
if (fTestContainerRadioButton.getSelection() && fContainerElement != null) {
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, fContainerElement.getHandleIdentifier());
//bug 26293
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$
} else {
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)fTestText.getText());
//bug 26293
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
}
config.setAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, fKeepRunning.getSelection());
}
/**
* @see ILaunchConfigurationTab#dispose()
*/
public void dispose() {
super.dispose();
fTestIcon.dispose();
fJavaElementLabelProvider.dispose();
}
/**
* @see AbstractLaunchConfigurationTab#getImage()
*/
public Image getImage() {
return fTestIcon;
}
/**
* Show a dialog that lists all main types
*/
protected void handleSearchButtonSelected() {
Shell shell = getShell();
IJavaProject javaProject = getJavaProject();
SelectionDialog dialog = new TestSelectionDialog(shell, new ProgressMonitorDialog(shell), javaProject);
dialog.setTitle(JUnitMessages.getString("JUnitMainTab.testdialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitMainTab.testdialog.message")); //$NON-NLS-1$
if (dialog.open() == SelectionDialog.CANCEL) {
return;
}
Object[] results = dialog.getResult();
if ((results == null) || (results.length < 1)) {
return;
}
IType type = (IType)results[0];
if (type != null) {
fTestText.setText(type.getFullyQualifiedName());
javaProject = type.getJavaProject();
fProjText.setText(javaProject.getElementName());
}
}
/**
* Show a dialog that lets the user select a project. This in turn provides
* context for the main type, allowing the user to key a main type name, or
* constraining the search for main types to the specified project.
*/
protected void handleProjectButtonSelected() {
IJavaProject project = chooseJavaProject();
if (project == null) {
return;
}
String projectName = project.getElementName();
fProjText.setText(projectName);
}
/**
* Realize a Java Project selection dialog and return the first selected project,
* or null if there was none.
*/
protected IJavaProject chooseJavaProject() {
IJavaProject[] projects;
try {
projects= JavaCore.create(getWorkspaceRoot()).getJavaProjects();
} catch (JavaModelException e) {
JUnitPlugin.log(e.getStatus());
projects= new IJavaProject[0];
}
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
dialog.setTitle(JUnitMessages.getString("JUnitMainTab.projectdialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitMainTab.projectdialog.message")); //$NON-NLS-1$
dialog.setElements(projects);
IJavaProject javaProject = getJavaProject();
if (javaProject != null) {
dialog.setInitialSelections(new Object[] { javaProject });
}
if (dialog.open() == ElementListSelectionDialog.OK) {
return (IJavaProject) dialog.getFirstResult();
}
return null;
}
/**
* Return the IJavaProject corresponding to the project name in the project name
* text field, or null if the text does not match a project name.
*/
protected IJavaProject getJavaProject() {
String projectName = fProjText.getText().trim();
if (projectName.length() < 1) {
return null;
}
return getJavaModel().getJavaProject(projectName);
}
/**
* Convenience method to get the workspace root.
*/
private IWorkspaceRoot getWorkspaceRoot() {
return ResourcesPlugin.getWorkspace().getRoot();
}
/**
* Convenience method to get access to the java model.
*/
private IJavaModel getJavaModel() {
return JavaCore.create(getWorkspaceRoot());
}
/**
* @see ILaunchConfigurationTab#isValid(ILaunchConfiguration)
*/
public boolean isValid(ILaunchConfiguration config) {
setErrorMessage(null);
setMessage(null);
String projectName = fProjText.getText().trim();
if (projectName.length() > 0) {
if (!ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).exists()) {
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.projectnotexists")); //$NON-NLS-1$
return false;
}
}
String testName = fTestText.getText().trim();
if (testName.length() == 0 && fContainerElement == null) {
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.testnotdefined")); //$NON-NLS-1$
return false;
}
// TO DO should verify that test exists
return true;
}
private void testModeChanged() {
boolean isSingleTestMode= fTestRadioButton.getSelection();
setEnableSingleTestGroup(isSingleTestMode);
setEnableContainerTestGroup(!isSingleTestMode);
}
private void setEnableContainerTestGroup(boolean enabled) {
fContainerSearchButton.setEnabled(enabled);
fContainerText.setEnabled(enabled);
}
private void setEnableSingleTestGroup(boolean enabled) {
fSearchButton.setEnabled(enabled && fProjText.getText().length() > 0);
fTestText.setEnabled(enabled);
fTestMethodLabel.setEnabled(enabled);
}
/**
* @see ILaunchConfigurationTab#setDefaults(ILaunchConfigurationWorkingCopy)
*/
public void setDefaults(ILaunchConfigurationWorkingCopy config) {
IJavaElement javaElement = getContext();
if (javaElement != null) {
initializeJavaProject(javaElement, config);
} else {
// We set empty attributes for project & main type so that when one config is
// compared to another, the existence of empty attributes doesn't cause an
// incorrect result (the performApply() method can result in empty values
// for these attributes being set on a config if there is nothing in the
// corresponding text boxes)
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
}
initializeTestAttributes(javaElement, config);
}
private void initializeTestAttributes(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
if (javaElement != null && javaElement.getElementType() < IJavaElement.COMPILATION_UNIT)
initializeTestContainer(javaElement, config);
else
initializeTestType(javaElement, config);
}
private void initializeTestContainer(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, javaElement.getHandleIdentifier());
initializeName(config, javaElement.getElementName());
}
private void initializeName(ILaunchConfigurationWorkingCopy config, String name) {
if (name == null) {
name= ""; //$NON-NLS-1$
}
if (name.length() > 0) {
int index = name.lastIndexOf('.');
if (index > 0) {
name = name.substring(index + 1);
}
name= getLaunchConfigurationDialog().generateName(name);
config.rename(name);
}
}
/**
* Set the main type & name attributes on the working copy based on the IJavaElement
*/
protected void initializeTestType(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
String name= ""; //$NON-NLS-1$
try {
// we only do a search for compilation units or class files or
// or source references
if ((javaElement instanceof ICompilationUnit) ||
(javaElement instanceof ISourceReference) ||
(javaElement instanceof IClassFile)) {
IType[] types = TestSearchEngine.findTests(new BusyIndicatorRunnableContext(), new Object[] {javaElement});
if ((types == null) || (types.length < 1)) {
return;
}
// Simply grab the first main type found in the searched element
name = types[0].getFullyQualifiedName();
}
} catch (InterruptedException ie) {
} catch (InvocationTargetException ite) {
}
if (name == null)
name= ""; //$NON-NLS-1$
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, name);
initializeName(config, name);
}
/**
* @see ILaunchConfigurationTab#getName()
*/
public String getName() {
return JUnitMessages.getString("JUnitMainTab.tab.label"); //$NON-NLS-1$
}
private IJavaElement chooseContainer(IJavaElement initElement) {
Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) {
public boolean isSelectedValid(Object element) {
return true;
}
};
acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses) {
public boolean select(Viewer viewer, Object parent, Object element) {
return super.select(viewer, parent, element);
}
};
StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider();
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
dialog.setValidator(validator);
dialog.setSorter(new JavaElementSorter());
dialog.setTitle(JUnitMessages.getString("JUnitMainTab.folderdialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitMainTab.folderdialog.message")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(JavaCore.create(getWorkspaceRoot()));
dialog.setInitialSelection(initElement);
dialog.setAllowMultiple(false);
if (dialog.open() == ElementTreeSelectionDialog.OK) {
Object element= dialog.getFirstResult();
return (IJavaElement)element;
}
return null;
}
private String getPresentationName(IJavaElement element) {
return fJavaElementLabelProvider.getText(element);
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/runner/MessageIds.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.runner;
/**
* Message identifiers for messages sent by the
* RemoteTestRunner.
*
* @see RemoteTestRunner
*/
public class MessageIds {
/**
* The header length of a message, all messages
* have a fixed header length
*/
public static final int MSG_HEADER_LENGTH= 8;
/**
* Notification that a test trace has started.
* The end of the trace is signaled by a Trace_END
* message. In between the TRACE_START and TRACE_END
* the stack trace is submitted as multiple lines.
*/
public static final String TRACE_START= "%TRACES "; //$NON-NLS-1$
/**
* Notification that a trace for a reran test has started.
* The end of the trace is signaled by a RTrace_END
* message.
*/
public static final String RTRACE_START= "%RTRACES"; //$NON-NLS-1$
/**
* Notification that a trace ends.
*/
public static final String TRACE_END= "%TRACEE "; //$NON-NLS-1$
/**
* Notification that a trace of a reran trace ends.
*/
public static final String RTRACE_END= "%RTRACEE"; //$NON-NLS-1$
/**
* Notification that a test run has started.
* MessageIds.TEST_RUN_START+testCount.toString
*/
public static final String TEST_RUN_START= "%TESTC "; //$NON-NLS-1$
/**
* Notification that a test has started.
* MessageIds.TEST_START + testName
*/
public static final String TEST_START= "%TESTS "; //$NON-NLS-1$
/**
* Notification that a test has started.
* TEST_END + testName
*/
public static final String TEST_END= "%TESTE "; //$NON-NLS-1$
/**
* Notification that a test had a error.
* TEST_ERROR + testName.
* After the notification follows the stack trace.
*/
public static final String TEST_ERROR= "%ERROR "; //$NON-NLS-1$
/**
* Notification that a test had a failure.
* TEST_FAILED + testName.
* After the notification follows the stack trace.
*/
public static final String TEST_FAILED= "%FAILED "; //$NON-NLS-1$
/**
* Notification that a test run has ended.
* TEST_RUN_END+elapsedTime.toString().
*/
public static final String TEST_RUN_END="%RUNTIME"; //$NON-NLS-1$
/**
* Notification that a test run was successfully stopped.
*/
public static final String TEST_STOPPED="%TSTSTP "; //$NON-NLS-1$
/**
* Notification that a test was reran.
* TEST_RERAN+testClass+" "+testName+STATUS.
* Status = "OK" or "FAILURE".
*/
public static final String TEST_RERAN= "%TSTRERN"; //$NON-NLS-1$
/**
* Notification about a test inside the test suite.
* TEST_TREE+testName","isSuite","testcount
* isSuite = "true" or "false"
*/
public static final String TEST_TREE="%TSTTREE"; //$NON-NLS-1$
/**
* Request to stop the current test run.
*/
public static final String TEST_STOP= ">STOP "; //$NON-NLS-1$
/**
* Request to rerun a test.
* TEST_RERUN+ClassName+" "+testName
*/
public static final String TEST_RERUN= ">RERUN "; //$NON-NLS-1$
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/runner/RemoteTestRunner.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.runner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Vector;
import junit.extensions.TestDecorator;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestFailure;
import junit.framework.TestListener;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import org.eclipse.jdt.internal.junit.ui.JUnitMessages;
/**
* A TestRunner that reports results via a socket connection.
* See MessageIds for more information about the protocl.
*/
public class RemoteTestRunner implements TestListener {
/**
* Holder for information for a rerun request
*/
private static class RerunRequest {
String fClassName;
String fTestName;
public RerunRequest(String className, String testName) {
fClassName= className;
fTestName= testName;
}
}
private static final String SUITE_METHODNAME= "suite"; //$NON-NLS-1$
/**
* The name of the test classes to be executed
*/
private String[] fTestClassNames;
/**
* The name of the test (argument -test)
*/
private String fTestName;
/**
* The current test result
*/
private TestResult fTestResult;
/**
* The client socket.
*/
private Socket fClientSocket;
/**
* Print writer for sending messages
*/
private PrintWriter fWriter;
/**
* Reader for incoming messages
*/
private BufferedReader fReader;
/**
* Host to connect to, default is the localhost
*/
private String fHost= ""; //$NON-NLS-1$
/**
* Port to connect to.
*/
private int fPort= -1;
/**
* Is the debug mode enabled?
*/
private boolean fDebugMode= false;
/**
* Keep the test run server alive after a test run has finished.
* This allows to rerun tests.
*/
private boolean fKeepAlive= false;
/**
* Has the server been stopped
*/
private boolean fStopped= false;
/**
* Queue of rerun requests.
*/
private Vector fRerunRequests= new Vector(10);
/**
* Reader thread that processes messages from the client.
*/
private class ReaderThread extends Thread {
public ReaderThread() {
super("ReaderThread"); //$NON-NLS-1$
}
public void run(){
try {
String message= null;
while (true) {
if ((message= fReader.readLine()) != null) {
if (message.startsWith(MessageIds.TEST_STOP)){
fStopped= true;
RemoteTestRunner.this.stop();
synchronized(RemoteTestRunner.this) {
RemoteTestRunner.this.notifyAll();
}
break;
}
else if (message.startsWith(MessageIds.TEST_RERUN)) {
String arg= message.substring(MessageIds.MSG_HEADER_LENGTH);
int c= arg.indexOf(" "); //$NON-NLS-1$
synchronized(RemoteTestRunner.this) {
fRerunRequests.add(new RerunRequest(arg.substring(0, c), arg.substring(c+1)));
RemoteTestRunner.this.notifyAll();
}
}
}
}
} catch (Exception e) {
RemoteTestRunner.this.stop();
}
}
}
/**
* The main entry point.
* Parameters<pre>
* -classnames: the name of the test suite class
* -testfilename: the name of a file containing classnames of test suites
* -test: the test method name (format classname testname)
* -host: the host to connect to default local host
* -port: the port to connect to, mandatory argument
* -keepalive: keep the process alive after a test run
* </pre>
*/
public static void main(String[] args) {
RemoteTestRunner testRunServer= new RemoteTestRunner();
testRunServer.init(args);
testRunServer.run();
// fix for 14434
System.exit(0);
}
/**
* Parse command line arguments. Hook for subclasses to process
* additional arguments.
*/
protected void init(String[] args) {
defaultInit(args);
}
/**
* The class loader to be used for loading tests.
* Subclasses may override to use another class loader.
*/
protected ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
/**
* Process the default arguments.
*/
protected final void defaultInit(String[] args) {
for(int i= 0; i < args.length; i++) {
if(args[i].toLowerCase().equals("-classnames") || args[i].toLowerCase().equals("-classname")){ //$NON-NLS-1$ //$NON-NLS-2$
Vector list= new Vector();
for (int j= i+1; j < args.length; j++) {
if (args[j].startsWith("-")) //$NON-NLS-1$
break;
list.add(args[j]);
}
fTestClassNames= (String[]) list.toArray(new String[list.size()]);
}
else if(args[i].toLowerCase().equals("-test")) { //$NON-NLS-1$
String testName= args[i+1];
int p= testName.indexOf(':');
if (p == -1)
throw new IllegalArgumentException("Testname not separated by \'%\'"); //$NON-NLS-1$
fTestName= testName.substring(p+1);
fTestClassNames= new String[]{ testName.substring(0, p) };
i++;
}
else if(args[i].toLowerCase().equals("-testnamefile")) { //$NON-NLS-1$
String testNameFile= args[i+1];
try {
readTestNames(testNameFile);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read testname file."); //$NON-NLS-1$
}
i++;
} else if(args[i].toLowerCase().equals("-port")) { //$NON-NLS-1$
fPort= Integer.parseInt(args[i+1]);
i++;
}
else if(args[i].toLowerCase().equals("-host")) { //$NON-NLS-1$
fHost= args[i+1];
i++;
}
else if(args[i].toLowerCase().equals("-keepalive")) { //$NON-NLS-1$
fKeepAlive= true;
}
else if(args[i].toLowerCase().equals("-debugging") || args[i].toLowerCase().equals("-debug")){ //$NON-NLS-1$ //$NON-NLS-2$
fDebugMode= true;
}
}
if(fTestClassNames == null || fTestClassNames.length == 0)
throw new IllegalArgumentException(JUnitMessages.getString("RemoteTestRunner.error.classnamemissing")); //$NON-NLS-1$
if (fPort == -1)
throw new IllegalArgumentException(JUnitMessages.getString("RemoteTestRunner.error.portmissing")); //$NON-NLS-1$
if (fDebugMode)
System.out.println("keepalive "+fKeepAlive); //$NON-NLS-1$
}
private void readTestNames(String testNameFile) throws IOException {
BufferedReader br= new BufferedReader(new FileReader(new File(testNameFile)));
try {
String line;
Vector list= new Vector();
while ((line= br.readLine()) != null) {
list.add(line);
}
fTestClassNames= (String[]) list.toArray(new String[list.size()]);
}
finally {
br.close();
}
if (fDebugMode) {
System.out.println("Tests:"); //$NON-NLS-1$
for (int i= 0; i < fTestClassNames.length; i++) {
System.out.println(" "+fTestClassNames[i]); //$NON-NLS-1$
}
}
}
/**
* Connects to the remote ports and runs the tests.
*/
protected void run() {
if (!connect()) {
return;
}
fTestResult= new TestResult();
fTestResult.addListener(this);
runTests(fTestClassNames, fTestName);
fTestResult.removeListener(this);
if (fTestResult != null) {
fTestResult.stop();
fTestResult= null;
}
if (fKeepAlive)
waitForReruns();
shutDown();
}
/**
* Waits for rerun requests until an explicit stop request
*/
private synchronized void waitForReruns() {
while (!fStopped) {
try {
wait();
if (!fStopped && fRerunRequests.size() > 0) {
RerunRequest r= (RerunRequest)fRerunRequests.remove(0);
rerunTest(r.fClassName, r.fTestName);
}
} catch (InterruptedException e) {
}
}
}
/**
* Returns the Test corresponding to the given suite.
*/
private Test getTest(String suiteClassName, String testName) {
Class testClass= null;
try {
testClass= loadSuiteClass(suiteClassName);
} catch (ClassNotFoundException e) {
String clazz= e.getMessage();
if (clazz == null)
clazz= suiteClassName;
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.classnotfound", clazz)); //$NON-NLS-1$
return null;
} catch(Exception e) {
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.exception", e.toString() )); //$NON-NLS-1$
return null;
}
if (testName != null) {
return createTest(testName, testClass);
}
Method suiteMethod= null;
try {
suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]);
} catch(Exception e) {
// try to extract a test suite automatically
return new TestSuite(testClass);
}
Test test= null;
try {
test= (Test)suiteMethod.invoke(null, new Class[0]); // static method
}
catch (InvocationTargetException e) {
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.invoke", e.getTargetException().toString() )); //$NON-NLS-1$
return null;
}
catch (IllegalAccessException e) {
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.invoke", e.toString() )); //$NON-NLS-1$
return null;
}
return test;
}
protected void runFailed(String message) {
System.err.println(message);
}
/**
* Loads the test suite class.
*/
private Class loadSuiteClass(String className) throws ClassNotFoundException {
if (className == null)
return null;
return getClassLoader().loadClass(className);
}
/**
* Runs a set of tests.
*/
private void runTests(String[] testClassNames, String testName) {
// instantiate all tests
Test[] suites= new Test[testClassNames.length];
for (int i= 0; i < suites.length; i++) {
suites[i]= getTest(testClassNames[i], testName);
}
// count all testMethods and inform ITestRunListeners
int count= countTests(suites);
notifyTestRunStarted(count);
if (count == 0) {
notifyTestRunEnded(0);
return;
}
long startTime= System.currentTimeMillis();
if (fDebugMode)
System.out.print("start send tree..."); //$NON-NLS-1$
for (int i= 0; i < suites.length; i++) {
sendTree(suites[i]);
}
if (fDebugMode)
System.out.println("done send tree - time(ms): "+(System.currentTimeMillis()-startTime)); //$NON-NLS-1$
long testStartTime= System.currentTimeMillis();
for (int i= 0; i < suites.length; i++) {
suites[i].run(fTestResult);
}
// inform ITestRunListeners of test end
if (fTestResult == null || fTestResult.shouldStop())
notifyTestRunStopped(System.currentTimeMillis() - testStartTime);
else
notifyTestRunEnded(System.currentTimeMillis() - testStartTime);
}
private int countTests(Test[] tests) {
int count= 0;
for (int i= 0; i < tests.length; i++) {
if (tests[i] != null)
count= count + tests[i].countTestCases();
}
return count;
}
/**
* Reruns a test as defined by the fully qualified class name and
* the name of the test.
*/
public void rerunTest(String className, String testName) {
Test reloadedTest= null;
try {
Class reloadedTestClass= getClassLoader().loadClass(className);
reloadedTest= createTest(testName, reloadedTestClass);
} catch(Exception e) {
reloadedTest= warning("Could not create test \'"+testName+"\'"); //$NON-NLS-1$ //$NON-NLS-2$
}
TestResult result= new TestResult();
reloadedTest.run(result);
notifyTestReran(result, className, testName);
}
/**
* Returns a test which will fail and log a warning message.
*/
private Test warning(final String message) {
return new TestCase("warning") { //$NON-NLS-1$
protected void runTest() {
fail(message);
}
};
}
private Test createTest(String testName, Class testClass) {
Class[] classArgs= { String.class };
Test test;
Constructor constructor= null;
try {
try {
constructor= testClass.getConstructor(classArgs);
test= (Test)constructor.newInstance(new Object[]{testName});
} catch (NoSuchMethodException e) {
// try the no arg constructor supported in 3.8.1
constructor= testClass.getConstructor(new Class[0]);
test= (Test)constructor.newInstance(new Object[0]);
if (test instanceof TestCase)
((TestCase) test).setName(testName);
}
if (test != null)
return test;
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
} catch (ClassCastException e) {
}
return warning("Could not create test \'"+testName+"\' "); //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see TestListener#addError(Test, Throwable)
*/
public final void addError(Test test, Throwable throwable) {
notifyTestFailed(MessageIds.TEST_ERROR, test.toString(), getTrace(throwable));
}
/*
* @see TestListener#addFailure(Test, AssertionFailedError)
*/
public final void addFailure(Test test, AssertionFailedError assertionFailedError) {
notifyTestFailed(MessageIds.TEST_FAILED, test.toString(), getTrace(assertionFailedError));
}
/*
* @see TestListener#endTest(Test)
*/
public void endTest(Test test) {
notifyTestEnded(test.toString());
}
/*
* @see TestListener#startTest(Test)
*/
public void startTest(Test test) {
notifyTestStarted(test.toString());
}
private void sendTree(Test test){
if(test instanceof TestDecorator){
TestDecorator decorator= (TestDecorator) test;
sendTree(decorator.getTest());
}
else if(test instanceof TestSuite){
TestSuite suite= (TestSuite) test;
notifyTestTreeEntry(suite.toString().trim() + ',' + true + ',' + suite.testCount());
for(int i=0; i < suite.testCount(); i++){
sendTree(suite.testAt(i));
}
}
else {
notifyTestTreeEntry(test.toString().trim() + ',' + false + ',' + test.countTestCases());
}
}
/**
* Returns the stack trace for the given throwable.
*/
private String getTrace(Throwable t) {
StringWriter stringWriter= new StringWriter();
PrintWriter writer= new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer= stringWriter.getBuffer();
return buffer.toString();
}
/**
* Stop the current test run.
*/
protected void stop() {
if (fTestResult != null) {
fTestResult.stop();
}
}
/**
* Connect to the remote test listener.
*/
private boolean connect() {
if (fDebugMode)
System.out.println("RemoteTestRunner: trying to connect" + fHost + ":" + fPort); //$NON-NLS-1$ //$NON-NLS-2$
Exception exception= null;
for (int i= 1; i < 20; i++) {
try{
fClientSocket= new Socket(fHost, fPort);
fWriter= new PrintWriter(fClientSocket.getOutputStream(), false/*true*/);
fReader= new BufferedReader(new InputStreamReader(fClientSocket.getInputStream()));
new ReaderThread().start();
return true;
} catch(IOException e){
exception= e;
}
try {
Thread.sleep(2000);
} catch(InterruptedException e) {
}
}
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.connect", new String[]{fHost, Integer.toString(fPort)} )); //$NON-NLS-1$
exception.printStackTrace();
return false;
}
/**
* Shutsdown the connection to the remote test listener.
*/
private void shutDown() {
if (fWriter != null) {
fWriter.close();
fWriter= null;
}
try {
if (fReader != null) {
fReader.close();
fReader= null;
}
} catch(IOException e) {
if (fDebugMode)
e.printStackTrace();
}
try {
if (fClientSocket != null) {
fClientSocket.close();
fClientSocket= null;
}
} catch(IOException e) {
if (fDebugMode)
e.printStackTrace();
}
}
private void sendMessage(String msg) {
if(fWriter == null)
return;
fWriter.println(msg);
}
private void notifyTestRunStarted(int testCount) {
sendMessage(MessageIds.TEST_RUN_START + testCount);
}
private void notifyTestRunEnded(long elapsedTime) {
sendMessage(MessageIds.TEST_RUN_END + elapsedTime);
fWriter.flush();
//shutDown();
}
private void notifyTestRunStopped(long elapsedTime) {
sendMessage(MessageIds.TEST_STOPPED + elapsedTime );
fWriter.flush();
//shutDown();
}
private void notifyTestStarted(String testName) {
sendMessage(MessageIds.TEST_START + testName);
fWriter.flush();
}
private void notifyTestEnded(String testName) {
sendMessage(MessageIds.TEST_END + testName);
}
private void notifyTestFailed(String status, String testName, String trace) {
sendMessage(status + testName);
sendMessage(MessageIds.TRACE_START);
sendMessage(trace);
sendMessage(MessageIds.TRACE_END);
fWriter.flush();
}
private void notifyTestTreeEntry(String treeEntry) {
sendMessage(MessageIds.TEST_TREE + treeEntry);
}
private void notifyTestReran(TestResult result, String testClass, String testName) {
TestFailure failure= null;
if (result.errorCount() > 0) {
failure= (TestFailure)result.errors().nextElement();
}
if (result.failureCount() > 0) {
failure= (TestFailure)result.failures().nextElement();
}
if (failure != null) {
Throwable t= failure.thrownException();
String trace= getTrace(t);
sendMessage(MessageIds.RTRACE_START);
sendMessage(trace);
sendMessage(MessageIds.RTRACE_END);
fWriter.flush();
}
String status= "OK"; //$NON-NLS-1$
if (result.errorCount() > 0)
status= "ERROR"; //$NON-NLS-1$
else if (result.failureCount() > 0)
status= "FAILURE"; //$NON-NLS-1$
if (fPort != -1) {
sendMessage(MessageIds.TEST_RERAN + testClass+" "+testName+" "+status); //$NON-NLS-1$ //$NON-NLS-2$
fWriter.flush();
}
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A view presenting the failed tests in a table.
*/
class FailureRunView implements ITestRunView, IMenuListener {
private Table fTable;
private TestRunnerViewPart fRunnerViewPart;
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fFailureTabIcon= TestRunnerViewPart.createImage("obj16/failures.gif"); //$NON-NLS-1$
public FailureRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fRunnerViewPart= runner;
CTabItem failureTab= new CTabItem(tabFolder, SWT.NONE);
failureTab.setText(getName());
failureTab.setImage(fFailureTabIcon);
Composite composite= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
composite.setLayout(gridLayout);
GridData gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
composite.setLayoutData(gridData);
fTable= new Table(composite, SWT.NONE);
gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
fTable.setLayout(gridLayout);
gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTable.setLayoutData(gridData);
failureTab.setControl(composite);
failureTab.setToolTipText(JUnitMessages.getString("FailureRunView.tab.tooltip")); //$NON-NLS-1$
initMenu();
addListeners();
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fFailureTabIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTable);
fTable.setMenu(menu);
}
public String getName() {
return JUnitMessages.getString("FailureRunView.tab.title"); //$NON-NLS-1$
}
public String getTestName() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return fTable.getItem(index).getText();
}
private String getClassName() {
return cutFromTo(getSelectedText(), '(', ')');
}
private String getMethodName() {
return cutTo(getSelectedText(), '(');
}
private static String cutFromTo(String string, char from, char to){
String modified= string;
modified= modified.substring(modified.indexOf(from) + 1);
return cutTo(modified, to);
}
private static String cutTo(String string, char to){
int toIndex= string.indexOf(to);
if (toIndex == -1)
return string;
else
return string.substring(0, toIndex);
}
public void menuAboutToShow(IMenuManager manager){
if (fTable.getSelectionCount() > 0) {
String className= getClassName();
String methodName= getMethodName();
if (className != null) {
manager.add(new OpenTestAction(fRunnerViewPart, className, methodName));
manager.add(new RerunAction(fRunnerViewPart, className, methodName));
}
}
}
private String getSelectedText() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return fTable.getItem(index).getText();
}
public void setSelectedTest(String testName){
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
TableItem tableItem= items[i];
if (tableItem.getText().equals(testName)){
fTable.setSelection(new TableItem[] { tableItem });
fTable.showItem(tableItem);
return;
}
}
}
public void setFocus() {
fTable.setFocus();
}
public void endTest(String testName){
TestRunInfo testInfo= fRunnerViewPart.getTestInfo(testName);
if(testInfo == null || testInfo.fStatus == ITestRunListener.STATUS_OK)
return;
TableItem tableItem= new TableItem(fTable, SWT.NONE);
updateTableItem(testInfo, tableItem);
fTable.showItem(tableItem);
}
private void updateTableItem(TestRunInfo testInfo, TableItem tableItem) {
tableItem.setText(testInfo.fTestName);
if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE)
tableItem.setImage(fFailureIcon);
else
tableItem.setImage(fErrorIcon);
tableItem.setData(testInfo);
}
private TableItem findItemByTest(String testName) {
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
if (items[i].getText().equals(testName))
return items[i];
}
return null;
}
public void activate() {
testSelected();
}
public void aboutToStart() {
fTable.removeAll();
}
protected void testSelected() {
fRunnerViewPart.handleTestSelected(getTestName());
}
protected void addListeners() {
fTable.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTable.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTable.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e){
handleDoubleClick(e);
}
public void mouseDown(MouseEvent e) {
activate();
}
public void mouseUp(MouseEvent e) {
activate();
}
});
}
public void handleDoubleClick(MouseEvent e) {
if (fTable.getSelectionCount() > 0)
new OpenTestAction(fRunnerViewPart, getClassName(), getMethodName()).run();
}
public void newTreeEntry(String treeEntry) {
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo)
*/
public void testStatusChanged(TestRunInfo info) {
TableItem item= findItemByTest(info.fTestName);
if (item != null) {
if (info.fStatus == ITestRunListener.STATUS_OK) {
item.dispose();
return;
}
updateTableItem(info, item);
}
if (item == null && info.fStatus != ITestRunListener.STATUS_OK) {
item= new TableItem(fTable, SWT.NONE);
updateTableItem(info, item);
}
if (item != null)
fTable.showItem(item);
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/HierarchyRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jdt.junit.ITestRunListener;
/*
* A view that shows the contents of a test suite
* as a tree.
*/
class HierarchyRunView implements ITestRunView, IMenuListener {
/**
* The tree widget
*/
private Tree fTree;
public static final int IS_SUITE= -1;
/**
* Helper used to resurrect test hierarchy
*/
private static class SuiteInfo {
public int fTestCount;
public TreeItem fTreeItem;
public SuiteInfo(TreeItem treeItem, int testCount){
fTreeItem= treeItem;
fTestCount= testCount;
}
}
/**
* Vector of SuiteInfo items
*/
private Vector fSuiteInfos= new Vector();
/**
* Maps test names to TreeItems.
* If there is one treeItem for a test then the
* value of the map corresponds to the item, otherwise
* there is a list of tree items.
*/
private Map fTreeItemMap= new HashMap();
private TestRunnerViewPart fTestRunnerPart;
private final Image fOkIcon= TestRunnerViewPart.createImage("obj16/testok.gif"); //$NON-NLS-1$
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fHierarchyIcon= TestRunnerViewPart.createImage("obj16/testhier.gif"); //$NON-NLS-1$
private final Image fSuiteIcon= TestRunnerViewPart.createImage("obj16/tsuite.gif"); //$NON-NLS-1$
private final Image fSuiteErrorIcon= TestRunnerViewPart.createImage("obj16/tsuiteerror.gif"); //$NON-NLS-1$
private final Image fSuiteFailIcon= TestRunnerViewPart.createImage("obj16/tsuitefail.gif"); //$NON-NLS-1$
private final Image fTestIcon= TestRunnerViewPart.createImage("obj16/test.gif"); //$NON-NLS-1$
public HierarchyRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fTestRunnerPart= runner;
CTabItem hierarchyTab= new CTabItem(tabFolder, SWT.NONE);
hierarchyTab.setText(getName());
hierarchyTab.setImage(fHierarchyIcon);
Composite testTreePanel= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
testTreePanel.setLayout(gridLayout);
GridData gridData= new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
testTreePanel.setLayoutData(gridData);
hierarchyTab.setControl(testTreePanel);
hierarchyTab.setToolTipText(JUnitMessages.getString("HierarchyRunView.tab.tooltip")); //$NON-NLS-1$
fTree= new Tree(testTreePanel, SWT.V_SCROLL);
gridData= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTree.setLayoutData(gridData);
initMenu();
addListeners();
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fOkIcon.dispose();
fHierarchyIcon.dispose();
fTestIcon.dispose();
fSuiteIcon.dispose();
fSuiteErrorIcon.dispose();
fSuiteFailIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTree);
fTree.setMenu(menu);
}
private String getTestLabel() {
TreeItem treeItem= fTree.getSelection()[0];
if(treeItem == null)
return ""; //$NON-NLS-1$
return treeItem.getText();
}
private TestRunInfo getTestInfo() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length == 0)
return null;
return ((TestRunInfo)treeItems[0].getData());
}
public String getClassName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return extractClassName(testInfo.fTestName);
}
public String getTestName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return testInfo.fTestName;
}
private String extractClassName(String testNameString) {
if (testNameString == null)
return null;
int index= testNameString.indexOf('(');
if (index < 0)
return testNameString;
testNameString= testNameString.substring(index + 1);
return testNameString.substring(0, testNameString.indexOf(')'));
}
public String getName() {
return JUnitMessages.getString("HierarchyRunView.tab.title"); //$NON-NLS-1$
}
public void setSelectedTest(String testName) {
TreeItem treeItem= findFirstItem(testName);
if (treeItem != null)
fTree.setSelection(new TreeItem[]{treeItem});
}
public void endTest(String testName) {
TreeItem treeItem= findFirstNotRunItem(testName);
// workaround for bug 8657
if (treeItem == null)
return;
TestRunInfo testInfo= fTestRunnerPart.getTestInfo(testName);
updateItem(treeItem, testInfo);
if (testInfo.fTrace != null)
fTree.showItem(treeItem);
}
private void updateItem(TreeItem treeItem, TestRunInfo testInfo) {
treeItem.setData(testInfo);
if(testInfo.fStatus == ITestRunListener.STATUS_OK) {
treeItem.setImage(fOkIcon);
return;
}
if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE)
treeItem.setImage(fFailureIcon);
else if (testInfo.fStatus == ITestRunListener.STATUS_ERROR)
treeItem.setImage(fErrorIcon);
propagateStatus(treeItem, testInfo.fStatus);
}
void propagateStatus(TreeItem item, int status) {
TreeItem parent= item.getParentItem();
if (parent == null)
return;
Image parentImage= parent.getImage();
if (status == ITestRunListener.STATUS_FAILURE) {
if (parentImage == fSuiteErrorIcon || parentImage == fSuiteFailIcon)
return;
parent.setImage(fSuiteFailIcon);
} else {
if (parentImage == fSuiteErrorIcon)
return;
parent.setImage(fSuiteErrorIcon);
}
propagateStatus(parent, status);
}
public void activate() {
testSelected();
}
public void setFocus() {
fTree.setFocus();
}
public void aboutToStart() {
fTree.removeAll();
fSuiteInfos.removeAllElements();
fTreeItemMap= new HashMap();
}
protected void testSelected() {
fTestRunnerPart.handleTestSelected(getTestName());
}
public void menuAboutToShow(IMenuManager manager) {
if (fTree.getSelectionCount() > 0) {
final TreeItem treeItem= fTree.getSelection()[0];
TestRunInfo testInfo= (TestRunInfo) treeItem.getData();
if (testInfo.fStatus == IS_SUITE) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
manager.add(new OpenTestAction(fTestRunnerPart, className));
} else {
manager.add(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel()));
manager.add(new RerunAction(fTestRunnerPart, getClassName(), getTestLabel()));
}
}
}
private void addListeners() {
fTree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTree.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTree.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e) {
handleDoubleClick(e);
}
});
}
void handleDoubleClick(MouseEvent e) {
TestRunInfo testInfo= getTestInfo();
if(testInfo == null)
return;
if ((testInfo.fStatus == IS_SUITE)) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
(new OpenTestAction(fTestRunnerPart, className)).run();
}
else {
(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel())).run();
}
}
public void newTreeEntry(String treeEntry) {
int index0= treeEntry.indexOf(',');
int index1= treeEntry.lastIndexOf(',');
String label= treeEntry.substring(0, index0).trim();
TestRunInfo testInfo= new TestRunInfo(label);
//fTestInfo.addElement(testInfo);
int index2;
if((index2= label.indexOf('(')) > 0)
label= label.substring(0, index2);
if((index2= label.indexOf('@')) > 0)
label= label.substring(0, index2);
String isSuite= treeEntry.substring(index0+1, index1);
int testCount= Integer.parseInt(treeEntry.substring(index1+1));
TreeItem treeItem;
while((fSuiteInfos.size() > 0) && (((SuiteInfo) fSuiteInfos.lastElement()).fTestCount == 0)) {
fSuiteInfos.removeElementAt(fSuiteInfos.size()-1);
}
if(fSuiteInfos.size() == 0){
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(fTree, SWT.NONE);
treeItem.setImage(fSuiteIcon);
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else if(isSuite.equals("true")) { //$NON-NLS-1$
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fHierarchyIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else {
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fTestIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
mapTest(testInfo, treeItem);
}
treeItem.setText(label);
treeItem.setData(testInfo);
}
private void mapTest(TestRunInfo info, TreeItem item) {
String test= info.fTestName;
Object o= fTreeItemMap.get(test);
if (o == null) {
fTreeItemMap.put(test, item);
return;
}
if (o instanceof TreeItem) {
List list= new ArrayList();
list.add(o);
list.add(item);
fTreeItemMap.put(test, list);
return;
}
if (o instanceof List) {
((List)o).add(item);
}
}
private TreeItem findFirstNotRunItem(String testName) {
Object o= fTreeItemMap.get(testName);
if (o instanceof TreeItem)
return (TreeItem)o;
if (o instanceof List) {
List l= (List)o;
for (int i= 0; i < l.size(); i++) {
TreeItem item= (TreeItem)l.get(i);
if (item.getImage() == fTestIcon)
return item;
}
return null;
}
return null;
}
private TreeItem findFirstItem(String testName) {
Object o= fTreeItemMap.get(testName);
if (o instanceof TreeItem)
return (TreeItem)o;
if (o instanceof List) {
return (TreeItem)((List)o).get(0);
}
return null;
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo, int)
*/
public void testStatusChanged(TestRunInfo newInfo) {
Object o= fTreeItemMap.get(newInfo.fTestName);
if (o instanceof TreeItem) {
updateItem((TreeItem)o, newInfo);
return;
}
if (o instanceof List) {
List l= (List)o;
for (int i= 0; i < l.size(); i++)
updateItem((TreeItem)l.get(i), newInfo);
}
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/ITestRunListener2.java
|
/*
* Created on Feb 8, 2003
*
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code Template
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* Extends ITestRunListener with a call back to trace the test contents
*/
public interface ITestRunListener2 extends ITestRunListener {
/**
* Information about a member of the test suite that is about to be run.
* The format of the string is:
* <pre>
* testName","isSuite","testcount
*
* testName: the name of the test
* isSuite: true or false depending on whether the test is a suite
* testCount: an integer indicating the number of tests
*
* Example: "testPass(junit.tests.MyTest),false,1"
* </pre>
*
* @param entry
*/
public void testTreeEntry(String description);
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/ITestRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
/**
* A TestRunView is shown as a page in a tabbed folder.
* It contributes the page contents and can return
* the currently selected test.
*/
interface ITestRunView {
/**
* Returns the name of the currently selected Test in the View
*/
public String getTestName();
/**
* Activates the TestRunView
*/
public void activate();
/**
* Sets the focus in the TestRunView
*/
public void setFocus();
/**
* Informs that the suite is about to start
*/
public void aboutToStart();
/**
* Returns the name of the RunView
*/
public String getName();
/**
* Sets the current Test in the View
*/
public void setSelectedTest(String testName);
/**
* A test has ended
*/
public void endTest(String testName);
/**
* The status of a test has changed
*/
public void testStatusChanged(TestRunInfo newInfo);
/**
* A new tree entry got posted.
*/
public void newTreeEntry(String treeEntry);
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitProgressBar.java
|
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
/**
* A progress bar with a red/green indication for success or failure.
*/
public class JUnitProgressBar extends Canvas {
private static final int DEFAULT_WIDTH = 160;
private static final int DEFAULT_HEIGHT = 18;
private int fCurrentTickCount= 0;
private int fMaxTickCount= 0;
private int fColorBarWidth= 0;
private boolean fError;
public JUnitProgressBar(Composite parent) {
super(parent, SWT.NONE);
addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
fColorBarWidth= scale(fCurrentTickCount);
redraw();
}
});
addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
paint(e);
}
});
}
public void setMaximum(int max) {
fMaxTickCount= max;
}
public void reset() {
fError= false;
fCurrentTickCount= 0;
fColorBarWidth= 0;
fMaxTickCount= 0;
redraw();
}
private void paintStep(int startX, int endX) {
GC gc = new GC(this);
setStatusColor(gc);
Rectangle rect= getClientArea();
startX= Math.max(1, startX);
gc.fillRectangle(startX, 1, endX-startX, rect.height-2);
gc.dispose();
}
private void setStatusColor(GC gc) {
if (fError)
gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_RED));
else
gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_GREEN));
}
private int scale(int value) {
if (fMaxTickCount > 0) {
Rectangle r= getClientArea();
if (r.width != 0)
return Math.max(0, value*(r.width-2)/fMaxTickCount);
}
return value;
}
private void drawBevelRect(GC gc, int x, int y, int w, int h, Color topleft, Color bottomright) {
gc.setForeground(topleft);
gc.drawLine(x, y, x+w-1, y);
gc.drawLine(x, y, x, y+h-1);
gc.setForeground(bottomright);
gc.drawLine(x+w, y, x+w, y+h);
gc.drawLine(x, y+h, x+w, y+h);
}
private void paint(PaintEvent event) {
GC gc = event.gc;
Display disp= getDisplay();
Rectangle rect= getClientArea();
gc.fillRectangle(rect);
drawBevelRect(gc, rect.x, rect.y, rect.width-1, rect.height-1,
disp.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW),
disp.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW));
setStatusColor(gc);
fColorBarWidth= Math.min(rect.width-2, fColorBarWidth);
gc.fillRectangle(1, 1, fColorBarWidth, rect.height-2);
}
public Point computeSize(int wHint, int hHint, boolean changed) {
checkWidget();
Point size= new Point(DEFAULT_WIDTH, DEFAULT_HEIGHT);
if (wHint != SWT.DEFAULT) size.x= wHint;
if (hHint != SWT.DEFAULT) size.y= hHint;
return size;
}
public void step(int failures) {
fCurrentTickCount++;
int x= fColorBarWidth;
fColorBarWidth= scale(fCurrentTickCount);
if (!fError && failures > 0) {
fError= true;
x= 1;
}
if (fCurrentTickCount == fMaxTickCount)
fColorBarWidth= getClientArea().width-1;
paintStep(x, fColorBarWidth);
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/RemoteTestRunnerClient.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Julien Ruaux: [email protected]
* Vincent Massol: [email protected]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.internal.junit.runner.MessageIds;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* The client side of the RemoteTestRunner. Handles the
* marshalling of th different messages.
*/
public class RemoteTestRunnerClient {
public abstract class ListenerSafeRunnable implements ISafeRunnable {
public void handleException(Throwable exception) {
JUnitPlugin.log(exception);
}
}
/**
* An array of listeners that are informed about test events.
*/
private ITestRunListener[] fListeners;
/**
* The server socket
*/
private ServerSocket fServerSocket;
private Socket fSocket;
private int fPort= -1;
private PrintWriter fWriter;
private BufferedReader fBufferedReader;
/**
* RemoteTestRunner is sending trace.
*/
private boolean fInReadTrace= false;
/**
* RemoteTestRunner is sending the rerun trace.
*/
private boolean fInReadRerunTrace= false;
/**
* The failed test that is currently reported from the RemoteTestRunner
*/
private String fFailedTest;
/**
* The failed trace that is currently reported from the RemoteTestRunner
*/
private String fFailedTrace;
/**
* The failed trace of a reran test
*/
private String fFailedRerunTrace;
/**
* The kind of failure of the test that is currently reported as failed
*/
private int fFailureKind;
private boolean fDebug= false;
/**
* Reads the message stream from the RemoteTestRunner
*/
private class ServerConnection extends Thread {
int fPort;
public ServerConnection(int port) {
super("ServerConnection"); //$NON-NLS-1$
fPort= port;
}
public void run() {
try {
if (fDebug)
System.out.println("Creating server socket "+fPort); //$NON-NLS-1$
fServerSocket= new ServerSocket(fPort);
fSocket= fServerSocket.accept();
fBufferedReader= new BufferedReader(new InputStreamReader(fSocket.getInputStream()));
fWriter= new PrintWriter(fSocket.getOutputStream(), true);
String message;
while(fBufferedReader != null && (message= readMessage(fBufferedReader)) != null)
receiveMessage(message);
} catch (SocketException e) {
notifyTestRunTerminated();
} catch (IOException e) {
System.out.println(e);
// fall through
}
shutDown();
}
}
/**
* Start listening to a test run. Start a server connection that
* the RemoteTestRunner can connect to.
*/
public synchronized void startListening(
ITestRunListener[] listeners,
int port) {
fListeners = listeners;
fPort = port;
ServerConnection connection = new ServerConnection(port);
connection.start();
}
/**
* Requests to stop the remote test run.
*/
public synchronized void stopTest() {
if (isRunning()) {
fWriter.println(MessageIds.TEST_STOP);
fWriter.flush();
}
}
/**
* Requests to rerun a test
*/
public synchronized void rerunTest(String className, String testName) {
if (isRunning()) {
fWriter.println(MessageIds.TEST_RERUN+className+" "+testName); //$NON-NLS-1$
fWriter.flush();
}
}
private synchronized void shutDown() {
if (fDebug)
System.out.println("shutdown "+fPort); //$NON-NLS-1$
if (fWriter != null) {
fWriter.close();
fWriter= null;
}
try {
if (fBufferedReader != null) {
fBufferedReader.close();
fBufferedReader= null;
}
} catch(IOException e) {
}
try{
if(fSocket != null) {
fSocket.close();
fSocket= null;
}
} catch(IOException e) {
}
try{
if(fServerSocket != null) {
fServerSocket.close();
fServerSocket= null;
}
} catch(IOException e) {
}
}
public boolean isRunning() {
return fSocket != null;
}
private String readMessage(BufferedReader in) throws IOException {
return in.readLine();
}
private void receiveMessage(String message) {
if (message.startsWith(MessageIds.TRACE_START)) {
fInReadTrace= true;
fFailedTrace= ""; //$NON-NLS-1$
return;
}
if (message.startsWith(MessageIds.TRACE_END)) {
fInReadTrace = false;
notifyTestFailed();
fFailedTrace = ""; //$NON-NLS-1$
return;
}
if (fInReadTrace) {
fFailedTrace+= message + '\n';
return;
}
if (message.startsWith(MessageIds.RTRACE_START)) {
fInReadRerunTrace= true;
fFailedRerunTrace= ""; //$NON-NLS-1$
return;
}
if (message.startsWith(MessageIds.RTRACE_END)) {
fInReadRerunTrace= false;
return;
}
if (fInReadRerunTrace) {
fFailedRerunTrace+= message + '\n';
return;
}
String arg= message.substring(MessageIds.MSG_HEADER_LENGTH);
if (message.startsWith(MessageIds.TEST_RUN_START)) {
int count = Integer.parseInt(arg);
notifyTestRunStarted(count);
return;
}
if (message.startsWith(MessageIds.TEST_START)) {
notifyTestStarted(arg);
return;
}
if (message.startsWith(MessageIds.TEST_END)) {
notifyTestEnded(arg);
return;
}
if (message.startsWith(MessageIds.TEST_ERROR)) {
fFailedTest= arg;
fFailureKind= ITestRunListener.STATUS_ERROR;
return;
}
if (message.startsWith(MessageIds.TEST_FAILED)) {
fFailedTest= arg;
fFailureKind= ITestRunListener.STATUS_FAILURE;
return;
}
if (message.startsWith(MessageIds.TEST_RUN_END)) {
long elapsedTime = Long.parseLong(arg);
testRunEnded(elapsedTime);
return;
}
if (message.startsWith(MessageIds.TEST_STOPPED)) {
long elapsedTime = Long.parseLong(arg);
notifyTestRunStopped(elapsedTime);
shutDown();
return;
}
if (message.startsWith(MessageIds.TEST_TREE)) {
notifyTestTreeEntry(arg);
return;
}
if (message.startsWith(MessageIds.TEST_RERAN)) {
// format: className" "testName" "status
// status: FAILURE, ERROR, OK
int c= arg.indexOf(" "); //$NON-NLS-1$
int t= arg.indexOf(" ", c+1); //$NON-NLS-1$
String className= arg.substring(0, c);
String testName= arg.substring(c+1, t);
String status= arg.substring(t+1);
int statusCode= ITestRunListener.STATUS_OK;
if (status.equals("FAILURE")) //$NON-NLS-1$
statusCode= ITestRunListener.STATUS_FAILURE;
else if (status.equals("ERROR")) //$NON-NLS-1$
statusCode= ITestRunListener.STATUS_ERROR;
String trace= ""; //$NON-NLS-1$
if (statusCode != ITestRunListener.STATUS_OK)
trace = fFailedRerunTrace;
// assumption a rerun trace was sent before
notifyTestReran(className, testName, statusCode, trace);
}
}
private void notifyTestReran(final String className, final String testName, final int statusCode, final String trace) {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testReran(className, testName, statusCode, trace);
}
});
}
}
private void notifyTestTreeEntry(final String treeEntry) {
for (int i= 0; i < fListeners.length; i++) {
if (fListeners[i] instanceof ITestRunListener2) {
ITestRunListener2 listener= (ITestRunListener2)fListeners[i];
listener.testTreeEntry(treeEntry);
}
}
}
private void notifyTestRunStopped(final long elapsedTime) {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testRunStopped(elapsedTime);
}
});
}
}
private void testRunEnded(final long elapsedTime) {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testRunEnded(elapsedTime);
}
});
}
}
private void notifyTestEnded(final String test) {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testEnded(test);
}
});
}
}
private void notifyTestStarted(final String test) {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testStarted(test);
}
});
}
}
private void notifyTestRunStarted(final int count) {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testRunStarted(count);
}
});
}
}
private void notifyTestFailed() {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testFailed(fFailureKind, fFailedTest, fFailedTrace);
}
});
}
}
private void notifyTestRunTerminated() {
for (int i= 0; i < fListeners.length; i++) {
final ITestRunListener listener= fListeners[i];
Platform.run(new ListenerSafeRunnable() {
public void run() {
listener.testRunTerminated();
}
});
}
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/RerunAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jface.action.Action;
/**
* Requests to rerun a test.
*/
public class RerunAction extends Action {
private String fClassName;
private String fTestName;
private TestRunnerViewPart fTestRunner;
/**
* Constructor for RerunAction.
*/
public RerunAction(TestRunnerViewPart runner, String className, String testName) {
super(JUnitMessages.getString("RerunAction.action.label")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.RERUN_ACTION);
fTestRunner= runner;
fClassName= className;
fTestName= testName;
}
/*
* @see IAction#run()
*/
public void run() {
fTestRunner.rerunTest(fClassName, fTestName);
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunInfo.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
/**
* Store information about an executed test.
*/
public class TestRunInfo extends Object {
public String fTestName;
public String fTrace;
public int fStatus;
public TestRunInfo(String testName){
fTestName= testName;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fTestName.hashCode();
}
/*
* @see Object#equals(Object)
*/
public boolean equals(Object obj) {
return fTestName.equals(obj);
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Julien Ruaux: [email protected]
* Vincent Massol: [email protected]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener2, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrors;
/**
* Number of failures during this test run
*/
protected int fFailures;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos = new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private TestRunInfo fFirstFailure;
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch= null;
/**
* Actions
*/
private Action fRerunLastTestAction;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
Image fOriginalViewImage= null;
IElementChangedListener fDirtyListener= null;
private class StopAction extends Action{
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action{
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void reset(){
reset(0);
setViewPartTitle(null);
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrors), String.valueOf(fFailures)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFirstFailure != null) {
fActiveRunView.setSelectedTest(fFirstFailure.fTestName);
handleTestSelected(fFirstFailure.fTestName);
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrors+fFailures > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testName) {
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$
TestRunInfo testInfo= getTestInfo(testName);
if (testInfo == null)
fTestInfos.put(testName, new TestRunInfo(testName));
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testName){
postEndTest(testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testName, String trace){
TestRunInfo testInfo= getTestInfo(testName);
if (testInfo == null) {
testInfo= new TestRunInfo(testName);
fTestInfos.put(testName, testInfo);
}
testInfo.fTrace= trace;
testInfo.fStatus= status;
if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
else
fFailures++;
if (fFirstFailure == null)
fFirstFailure= testInfo;
// show the view on the first error only
if (fShowOnErrorOnly && (fErrors + fFailures == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
String test= testName+"("+className+")"; //$NON-NLS-1$ //$NON-NLS-2$
TestRunInfo info= getTestInfo(test);
updateTest(info, status);
if (info.fTrace == null || !info.fTrace.equals(trace)) {
info.fTrace= trace;
showFailure(info.fTrace);
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.fStatus)
return;
if (info.fStatus == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailures++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
} else if (info.fStatus == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrors--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrors--;
fFailures++;
}
} else if (info.fStatus == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailures--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailures--;
fErrors++;
}
}
info.fStatus= status;
final TestRunInfo finalInfo= info;
postAsyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
Vector listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.copyInto(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public void rerunTest(String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
getSite().getKeyBindingService().unregisterAction(fRerunLastTestAction);
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void postAsyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
}
}
});
}
private void postEndTest(final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testName);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailures+fErrors);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrors, fFailures);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrors);
fCounterPanel.setFailureValue(fFailures);
fCounterPanel.setRunValue(fExecutedTests);
}
protected void postShowTestResultsView() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getTestName());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
SashForm sashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(sashForm, SWT.NONE);
CTabFolder tabFolder= createTestRunViews(top);
tabFolder.setLayoutData(new TabFolderLayout());
top.setContent(tabFolder);
ViewForm bottom= new ViewForm(sashForm, SWT.NONE);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, this);
bottom.setContent(fFailureView.getComposite());
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
// fill the failure trace viewer toolbar
ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar);
failureToolBarmanager.add(new EnableStackFilterAction(fFailureView));
failureToolBarmanager.update(true);
sashForm.setWeights(new int[]{50, 50});
return sashForm;
}
private void reset(final int testCount) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailures= 0;
fErrors= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFirstFailure= null;
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
parent.setLayout(gridLayout);
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fRerunLastTestAction= new RerunLastAction();
fRerunLastTestAction.setActionDefinitionId("org.eclipse.jdt.junit.reruntest"); //$NON-NLS-1$
toolBar.add(new StopAction());
toolBar.add(fRerunLastTestAction);
actionBars.updateActionBars();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
actionBars.setGlobalActionHandler(
IWorkbenchActionConstants.COPY,
new CopyTraceAction(fFailureView));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
getSite().getKeyBindingService().registerAction(fRerunLastTestAction);
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testName) {
if (testName == null)
return null;
return (TestRunInfo) fTestInfos.get(testName);
}
public void handleTestSelected(String testName) {
TestRunInfo testInfo= getTestInfo(testName);
if (testInfo == null) {
showFailure(""); //$NON-NLS-1$
} else {
showFailure(testInfo.fTrace);
}
}
private void showFailure(final String failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/util/JUnitStubUtility.java
|
/*
* Copyright (c) 2002 IBM Corp. All rights reserved.
* This file is 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
*/
package org.eclipse.jdt.internal.junit.util;
import org.eclipse.swt.SWT;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICodeFormatter;
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.core.ToolFactory;
import org.eclipse.jdt.ui.wizards.NewTypeWizardPage.ImportsManager;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
/**
* Utility methods for code generation.
* TODO: some methods are duplicated from org.eclipse.jdt.ui
*/
public class JUnitStubUtility {
public static class GenStubSettings extends CodeGenerationSettings {
public boolean fCallSuper;
public boolean fMethodOverwrites;
public boolean fNoBody;
public GenStubSettings(CodeGenerationSettings settings) {
this.createComments= settings.createComments;
this.createNonJavadocComments= settings.createNonJavadocComments;
}
}
/**
* Examines a string and returns the first line delimiter found.
*/
public static String getLineDelimiterUsed(IJavaElement elem) {
try {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null && cu.exists()) {
IBuffer buf= cu.getBuffer();
int length= buf.getLength();
for (int i= 0; i < length; i++) {
char ch= buf.getChar(i);
if (ch == SWT.CR) {
if (i + 1 < length) {
if (buf.getChar(i + 1) == SWT.LF) {
return "\r\n"; //$NON-NLS-1$
}
}
return "\r"; //$NON-NLS-1$
} else if (ch == SWT.LF) {
return "\n"; //$NON-NLS-1$
}
}
}
return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (JavaModelException e) {
return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public static String codeFormat(String sourceString, int initialIndentationLevel, String lineDelim) {
ICodeFormatter formatter= ToolFactory.createDefaultCodeFormatter(null);
return formatter.format(sourceString, initialIndentationLevel, null, lineDelim);
}
/**
* Generates a stub. Given a template method, a stub with the same signature
* will be constructed so it can be added to a type.
* @param destTypeName The name of the type to which the method will be added to (Used for the constructor)
* @param method A method template (method belongs to different type than the parent)
* @param options Options as defined abouve (GENSTUB_*)
* @param imports Imports required by the sub are added to the imports structure
* @throws JavaModelException
*/
public static String genStub(String destTypeName, IMethod method, GenStubSettings settings, ImportsManager imports) throws JavaModelException {
IType declaringtype= method.getDeclaringType();
StringBuffer buf= new StringBuffer();
String[] paramTypes= method.getParameterTypes();
String[] paramNames= method.getParameterNames();
String[] excTypes= method.getExceptionTypes();
String retTypeSig= method.getReturnType();
int lastParam= paramTypes.length -1;
if (settings.createComments) {
if (method.isConstructor()) {
String desc= "Constructor for " + destTypeName; //$NON-NLS-1$
genJavaDocStub(desc, paramNames, Signature.SIG_VOID, excTypes, buf);
} else {
// java doc
if (settings.fMethodOverwrites) {
boolean isDeprecated= Flags.isDeprecated(method.getFlags());
genJavaDocSeeTag(declaringtype.getElementName(), method.getElementName(), paramTypes, settings.createNonJavadocComments, isDeprecated, buf);
} else {
// generate a default java doc comment
String desc= "Method " + method.getElementName(); //$NON-NLS-1$
genJavaDocStub(desc, paramNames, retTypeSig, excTypes, buf);
}
}
}
int flags= method.getFlags();
if (Flags.isPublic(flags) || (declaringtype.isInterface() && !settings.fNoBody)) {
buf.append("public "); //$NON-NLS-1$
} else if (Flags.isProtected(flags)) {
buf.append("protected "); //$NON-NLS-1$
} else if (Flags.isPrivate(flags)) {
buf.append("private "); //$NON-NLS-1$
}
if (Flags.isSynchronized(flags)) {
buf.append("synchronized "); //$NON-NLS-1$
}
if (Flags.isVolatile(flags)) {
buf.append("volatile "); //$NON-NLS-1$
}
if (Flags.isStrictfp(flags)) {
buf.append("strictfp "); //$NON-NLS-1$
}
if (Flags.isStatic(flags)) {
buf.append("static "); //$NON-NLS-1$
}
if (method.isConstructor()) {
buf.append(destTypeName);
} else {
String retTypeFrm= Signature.toString(retTypeSig);
if (!isBuiltInType(retTypeSig)) {
resolveAndAdd(retTypeSig, declaringtype, imports);
}
buf.append(Signature.getSimpleName(retTypeFrm));
buf.append(' ');
buf.append(method.getElementName());
}
buf.append('(');
for (int i= 0; i <= lastParam; i++) {
String paramTypeSig= paramTypes[i];
String paramTypeFrm= Signature.toString(paramTypeSig);
if (!isBuiltInType(paramTypeSig)) {
resolveAndAdd(paramTypeSig, declaringtype, imports);
}
buf.append(Signature.getSimpleName(paramTypeFrm));
buf.append(' ');
buf.append(paramNames[i]);
if (i < lastParam) {
buf.append(", "); //$NON-NLS-1$
}
}
buf.append(')');
int lastExc= excTypes.length - 1;
if (lastExc >= 0) {
buf.append(" throws "); //$NON-NLS-1$
for (int i= 0; i <= lastExc; i++) {
String excTypeSig= excTypes[i];
String excTypeFrm= Signature.toString(excTypeSig);
resolveAndAdd(excTypeSig, declaringtype, imports);
buf.append(Signature.getSimpleName(excTypeFrm));
if (i < lastExc) {
buf.append(", "); //$NON-NLS-1$
}
}
}
if (settings.fNoBody) {
buf.append(";\n\n"); //$NON-NLS-1$
} else {
buf.append(" {\n\t"); //$NON-NLS-1$
if (!settings.fCallSuper) {
if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) {
buf.append('\t');
if (!isBuiltInType(retTypeSig) || Signature.getArrayCount(retTypeSig) > 0) {
buf.append("return null;\n\t"); //$NON-NLS-1$
} else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) {
buf.append("return false;\n\t"); //$NON-NLS-1$
} else {
buf.append("return 0;\n\t"); //$NON-NLS-1$
}
}
} else {
buf.append('\t');
if (!method.isConstructor()) {
if (!Signature.SIG_VOID.equals(retTypeSig)) {
buf.append("return "); //$NON-NLS-1$
}
buf.append("super."); //$NON-NLS-1$
buf.append(method.getElementName());
} else {
buf.append("super"); //$NON-NLS-1$
}
buf.append('(');
for (int i= 0; i <= lastParam; i++) {
buf.append(paramNames[i]);
if (i < lastParam) {
buf.append(", "); //$NON-NLS-1$
}
}
buf.append(");\n\t"); //$NON-NLS-1$
}
buf.append("}\n\n"); //$NON-NLS-1$
}
return buf.toString();
}
/**
* Generates a default JavaDoc comment stub for a method.
*/
private static void genJavaDocStub(String descr, String[] paramNames, String retTypeSig, String[] excTypeSigs, StringBuffer buf) {
buf.append("/**\n"); //$NON-NLS-1$
buf.append(" * "); buf.append(descr); buf.append(".\n"); //$NON-NLS-2$ //$NON-NLS-1$
for (int i= 0; i < paramNames.length; i++) {
buf.append(" * @param "); buf.append(paramNames[i]); buf.append('\n'); //$NON-NLS-1$
}
if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) {
String simpleName= Signature.getSimpleName(Signature.toString(retTypeSig));
buf.append(" * @return "); buf.append(simpleName); buf.append('\n'); //$NON-NLS-1$
}
for (int i= 0; i < excTypeSigs.length; i++) {
String simpleName= Signature.getSimpleName(Signature.toString(excTypeSigs[i]));
buf.append(" * @throws "); buf.append(simpleName); buf.append('\n'); //$NON-NLS-1$
}
buf.append(" */\n"); //$NON-NLS-1$
}
/**
* Generates a '@see' tag to the defined method.
*/
public static void genJavaDocSeeTag(String declaringTypeName, String methodName, String[] paramTypes, boolean nonJavaDocComment, boolean isDeprecated, StringBuffer buf) {
// create a @see link
buf.append("/*"); //$NON-NLS-1$
if (!nonJavaDocComment) {
buf.append('*');
}
buf.append("\n * @see "); //$NON-NLS-1$
buf.append(declaringTypeName);
buf.append('#');
buf.append(methodName);
buf.append('(');
for (int i= 0; i < paramTypes.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(Signature.getSimpleName(Signature.toString(paramTypes[i])));
}
buf.append(")\n"); //$NON-NLS-1$
if (isDeprecated) {
buf.append(" * @deprecated\n"); //$NON-NLS-1$
}
buf.append(" */\n"); //$NON-NLS-1$
}
private static boolean isBuiltInType(String typeName) {
char first= Signature.getElementType(typeName).charAt(0);
return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED);
}
private static void resolveAndAdd(String refTypeSig, IType declaringType, ImportsManager imports) throws JavaModelException {
String resolvedTypeName= JavaModelUtil.getResolvedTypeName(refTypeSig, declaringType);
if (resolvedTypeName != null) {
imports.addImport(resolvedTypeName);
}
}
public static String getTodoTaskTag(IJavaProject project) {
String markers= null;
if (project == null) {
markers= JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS);
} else {
markers= project.getOption(JavaCore.COMPILER_TASK_TAGS, true);
}
if (markers != null && markers.length() > 0) {
int idx= markers.indexOf(',');
if (idx == -1) {
return markers;
} else {
return markers.substring(0, idx);
}
}
return null;
}
}
|
14,702 |
Bug 14702 JUnit plugin displays incorrect Failure Trace when using JUnit decorator
|
The suite method we're running: public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TD_DecoratorOne(new TestSuite(TC_SomeTest.class))); suite.addTest(new TD_DecoratorTwo(new TestSuite(TC_SomeTest.class))); return suite; } // One of the methods in TC_SomeTest protected void testQuery() { ... some assertEquals()... with a customized message reflecting the decorator that was run. } Assume testQuery() fails when run in each decorator (our decorators are subclasses of TestSetup). System.out.println() reflects the customized message. The JUnit SwingUI reflects the customized message. The JUnit TextUI reflects the customized message. The Eclipse JUnit plugin Failure Trace shows the message for the most recent failure for BOTH failures rather than the correct customized message for each failure. We think the potential source of the problem is that the 2 tests have the same name and it looks like TestRunInfo is basing the failure trace display on the test name (see the equals() method). This may not be the source of the problem...just a guess after looking at the plugin for about 10 minutes. Due to this problem, we really can't depend on the JUnit plugin whenever we use decorators, because the failure message isn't accurate. Other than this issue, we're quite fond of the JUnit plugin and would love to use it.
|
resolved fixed
|
cf07989
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-26T23:39:31Z | 2002-04-25T21:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/ITestRunListener.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.junit;
/**
* A listener interface for observing the execution of a test run.
* <p>
* Clients contributing to the org.eclipse.jdt.junit.testRunListener
* extension point implement this interface.
*
* @since 2.1
*/
public interface ITestRunListener {
/**
* Test passed.
*
* @see ITestRunListener#testFailed
*/
public static final int STATUS_OK= 0;
/**
* Test had an error an unanticipated exception occurred.
*
* @see ITestRunListener#testFailed
*/
public static final int STATUS_ERROR= 1;
/**
* Test had a failure an assertion failed.
*
* @see ITestRunListener#testFailed
*/
public static final int STATUS_FAILURE= 2;
/**
* A test run has started.
*
* @param testCount the number of tests that will be run.
*/
public void testRunStarted(int testCount);
/**
* A test run ended.
*
* @param elapsedTime the elapsed time of the test run.
*/
public void testRunEnded(long elapsedTime);
/**
* A test run was stopped before it ended.
*/
public void testRunStopped(long elapsedTime);
/**
* A test started.
*
* @param elapsedTime the elapsed time of the test until it got stopped.
*/
public void testStarted(String testName);
/**
* A test ended.
*
* @param testName the name of the test that has started
*/
public void testEnded(String testName);
/**
* A test failed.
*
* @param testName the name of the test that has ended.
* @param status the status of the test.
* @param trace the stack trace in the case of a failure.
*/
public void testFailed(int status, String testName, String trace);
/**
* The test runner VM has terminated.
*
*/
public void testRunTerminated();
/**
* A single test was reran.
* @param testClass the name of the test class.
* @param testName the name of the test.
* @param status the status of the run
* @param trace the stack trace in the case of a failure.
*/
public void testReran(String testClass, String testName, int status, String trace);
}
|
32,301 |
Bug 32301 2 Packages with similar names have a problem displaying in the Java browsing perspective.
|
Hello, Thanks for a wonderful IDE with all these rich features. I think we have a small bug in the Java Browsing Perspective. As an example: Please create a package called "test" in your project. Then create a parallel package called "test_a". After refreshing project, test_a will show up as a child of "test" and also as its parallel project. "test_a" is actually a parallel package, and should show up only alongside "test", not under it. Thanks, agam
|
resolved fixed
|
3fd4644
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T08:39:55Z | 2003-02-20T00:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/PackagesViewHierarchicalContentProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
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;
/**
* Tree content provider for the hierarchical layout in the packages view.
* <p>
* XXX: The standard Java browsing part content provider needs and calls
* the browsing part/view. This class currently doesn't need to do so
* but might be required to later.
* </p>
*/
class PackagesViewHierarchicalContentProvider extends LogicalPackagesProvider implements ITreeContentProvider {
public PackagesViewHierarchicalContentProvider(StructuredViewer viewer){
super(viewer);
}
/*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
try {
if (parentElement instanceof IJavaElement) {
IJavaElement iJavaElement= (IJavaElement) parentElement;
int type= iJavaElement.getElementType();
switch (type) {
case IJavaElement.JAVA_PROJECT :
{
//create new element mapping
fMapToLogicalPackage.clear();
fMapToPackageFragments.clear();
IJavaProject project= (IJavaProject) parentElement;
IPackageFragment[] topLevelChildren= getTopLevelChildrenByElementName(project.getPackageFragments());
List list= new ArrayList();
for (int i= 0; i < topLevelChildren.length; i++) {
IPackageFragment fragment= topLevelChildren[i];
IJavaElement el= fragment.getParent();
if (el instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) el;
if (!root.isArchive() || !root.isExternal())
list.add(fragment);
}
}
return combineSamePackagesIntoLogialPackages((IPackageFragment[]) list.toArray(new IPackageFragment[list.size()]));
}
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
{
IPackageFragmentRoot root= (IPackageFragmentRoot) parentElement;
//create new element mapping
fMapToLogicalPackage.clear();
fMapToPackageFragments.clear();
IResource resource= root.getUnderlyingResource();
IPackageFragment[] fragments= new IPackageFragment[0];
if (root.isArchive()) {
IJavaElement[] els= root.getChildren();
fragments= getTopLevelChildrenByElementName(els);
} else if (resource != null && resource instanceof IFolder) {
fragments= getTopLevelChildrenByElementName(root.getChildren());
}
addFragmentsToMap(fragments);
return fragments;
}
case IJavaElement.PACKAGE_FRAGMENT :
{
IPackageFragment packageFragment= (IPackageFragment) parentElement;
IPackageFragment[] fragments= new IPackageFragment[0];
IJavaElement parent= packageFragment.getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
fragments= findNextLevelChildrenByElementName(root, packageFragment);
}
addFragmentsToMap(fragments);
return fragments;
}
}
//@Improve: rewrite using concatenate
} else if (parentElement instanceof LogicalPackage) {
List children= new ArrayList();
LogicalPackage logicalPackage= (LogicalPackage) parentElement;
IPackageFragment[] elements= logicalPackage.getFragments();
for (int i= 0; i < elements.length; i++) {
IPackageFragment fragment= elements[i];
IPackageFragment[] objects= findNextLevelChildrenByElementName((IPackageFragmentRoot) fragment.getParent(), fragment);
children.addAll(Arrays.asList(objects));
}
return combineSamePackagesIntoLogialPackages((IPackageFragment[]) children.toArray(new IPackageFragment[children.size()]));
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return new Object[0];
}
private IPackageFragment[] findNextLevelChildrenByElementName(IPackageFragmentRoot parent, IPackageFragment fragment) {
List list= new ArrayList();
try {
IJavaElement[] children= parent.getChildren();
String fragmentname= fragment.getElementName();
for (int i= 0; i < children.length; i++) {
IJavaElement element= children[i];
if (element instanceof IPackageFragment) {
IPackageFragment frag= (IPackageFragment) element;
String name= element.getElementName();
if (frag.exists() && !IPackageFragment.DEFAULT_PACKAGE_NAME.equals(fragmentname) && name.startsWith(fragmentname) && !name.equals(fragmentname)) {
String tail= name.substring(fragmentname.length() + 1);
if (!IPackageFragment.DEFAULT_PACKAGE_NAME.equals(tail) && (tail.indexOf(".") == -1)) { //$NON-NLS-1$
list.add(frag);
}
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return (IPackageFragment[]) list.toArray(new IPackageFragment[list.size()]);
}
private IPackageFragment[] getTopLevelChildrenByElementName(IJavaElement[] elements){
List topLevelElements= new ArrayList();
for (int i= 0; i < elements.length; i++) {
IJavaElement iJavaElement= elements[i];
//if the name of the PackageFragment is the top level package it will contain no "." separators
if((iJavaElement.getElementName().indexOf(".")==-1) && (iJavaElement instanceof IPackageFragment)){ //$NON-NLS-1$
topLevelElements.add(iJavaElement);
}
}
return (IPackageFragment[]) topLevelElements.toArray(new IPackageFragment[topLevelElements.size()]);
}
/*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
try {
if (element instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment) element;
if(!fragment.exists())
return null;
Object parent= getHierarchicalParent(fragment);
if(parent instanceof IPackageFragment) {
IPackageFragment pkgFragment= (IPackageFragment)parent;
LogicalPackage logicalPkg= findLogicalPackage(pkgFragment);
if (logicalPkg != null)
return logicalPkg;
else {
LogicalPackage lp= createLogicalPackage(pkgFragment);
if(lp == null)
return pkgFragment;
else return lp;
}
}
return parent;
} else if(element instanceof LogicalPackage){
LogicalPackage el= (LogicalPackage) element;
IPackageFragment fragment= el.getFragments()[0];
Object parent= getHierarchicalParent(fragment);
if(parent instanceof IPackageFragment){
IPackageFragment pkgFragment= (IPackageFragment) parent;
LogicalPackage logicalPkg= findLogicalPackage(pkgFragment);
if (logicalPkg != null)
return logicalPkg;
else {
LogicalPackage lp= createLogicalPackage(pkgFragment);
if(lp == null)
return pkgFragment;
else return lp;
}
} else
return fragment.getJavaProject();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
/*
* Check if the given IPackageFragment should be the member of a
* LogicalPackage and if so creates the LogicalPackage and adds it to the
* map.
*/
private LogicalPackage createLogicalPackage(IPackageFragment pkgFragment) {
if(!fInputIsProject)
return null;
List fragments= new ArrayList();
try {
IPackageFragmentRoot[] roots= pkgFragment.getJavaProject().getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
IPackageFragment fragment= root.getPackageFragment(pkgFragment.getElementName());
if(fragment.exists() && !fragment.equals(pkgFragment))
fragments.add(fragment);
}
if(!fragments.isEmpty()) {
LogicalPackage logicalPackage= new LogicalPackage(pkgFragment);
fMapToLogicalPackage.put(getKey(pkgFragment), logicalPackage);
Iterator iter= fragments.iterator();
while(iter.hasNext()){
IPackageFragment f= (IPackageFragment)iter.next();
if(logicalPackage.belongs(f)){
logicalPackage.add(f);
fMapToLogicalPackage.put(getKey(f), logicalPackage);
}
}
return logicalPackage;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
private Object getHierarchicalParent(IPackageFragment fragment) throws JavaModelException {
IJavaElement parent= fragment.getParent();
if ((parent instanceof IPackageFragmentRoot) && parent.exists()) {
IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
if (root.isArchive() || !fragment.exists()) {
return findNextLevelParentByElementName(fragment, root);
} else {
IResource resource= fragment.getUnderlyingResource();
if ((resource != null) && (resource instanceof IFolder)) {
IFolder folder= (IFolder) resource;
IResource res= folder.getParent();
IJavaElement el= JavaCore.create(res);
return el;
}
}
}
return parent;
}
private Object findNextLevelParentByElementName(IJavaElement child, IJavaElement parent) {
String name= child.getElementName();
if(name.indexOf(".")==-1) //$NON-NLS-1$
return parent;
try {
String realParentName= child.getElementName().substring(0,name.lastIndexOf(".")); //$NON-NLS-1$
IJavaElement[] children= new IJavaElement[0];
if(parent instanceof IPackageFragmentRoot){
IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
children= root.getChildren();
} else if(parent instanceof IJavaProject){
IJavaProject project= (IJavaProject) parent;
children= project.getPackageFragments();
}
for (int i= 0; i < children.length; i++) {
IJavaElement element= children[i];
if(element.getElementName().equals(realParentName))
return element;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return parent;
}
/*
* @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
if (element instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment) element;
if(fragment.isDefaultPackage() || !fragment.exists())
return false;
}
return getChildren(element).length > 0;
}
/*
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
protected void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind = delta.getKind();
final IJavaElement element = delta.getElement();
if (element instanceof IPackageFragment) {
final IPackageFragment frag = (IPackageFragment) element;
//if fragment was in LogicalPackage refresh,
//otherwise just remove
if (kind == IJavaElementDelta.REMOVED) {
removeElement(frag);
return;
} else if (kind == IJavaElementDelta.ADDED) {
Object parent= getParent(frag);
addElement(frag, parent);
return;
} else if (kind == IJavaElementDelta.CHANGED) {
//just refresh
LogicalPackage logicalPkg= findLogicalPackage(frag);
//in case changed object is filtered out
if (logicalPkg != null)
postRefresh(findElementToRefresh(logicalPkg));
else
postRefresh(findElementToRefresh(frag));
return;
}
}
processAffectedChildren(delta);
}
private Object findElementToRefresh(Object object) {
Object toBeRefreshed= object;
if (fViewer.testFindItem(object) == null) {
Object parent= getParent(object);
if(parent instanceof IPackageFragmentRoot && fInputIsProject)
parent= ((IPackageFragmentRoot)parent).getJavaProject();
if(parent != null)
toBeRefreshed= parent;
}
return toBeRefreshed;
}
private void processAffectedChildren(IJavaElementDelta delta) throws JavaModelException {
IJavaElementDelta[] affectedChildren = delta.getAffectedChildren();
for (int i = 0; i < affectedChildren.length; i++) {
if (!(affectedChildren[i] instanceof ICompilationUnit)) {
processDelta(affectedChildren[i]);
}
}
}
private void postAdd(final Object child, final Object parent) {
postRunnable(new Runnable() {
public void run() {
Control ctrl = fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
((TreeViewer)fViewer).add(parent, child);
}
}
});
}
private void postRemove(final Object object) {
postRunnable(new Runnable() {
public void run() {
Control ctrl = fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
((TreeViewer)fViewer).remove(object);
}
}
});
}
private void postRefresh(final Object object) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
((TreeViewer) fViewer).refresh(object);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
// fBrowsingPart.setProcessSelectionEvents(false);
try {
Display currentDisplay= Display.getCurrent();
if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()))
ctrl.getDisplay().syncExec(r);
else
ctrl.getDisplay().asyncExec(r);
} finally {
// fBrowsingPart.setProcessSelectionEvents(true);
}
}
}
private void addElement(IPackageFragment frag, Object parent) {
String key= getKey(frag);
LogicalPackage lp= (LogicalPackage)fMapToLogicalPackage.get(key);
//if fragment must be added to an existing LogicalPackage
if (lp != null && lp.belongs(frag)){
lp.add(frag);
return;
}
//if a new LogicalPackage must be created
IPackageFragment iPackageFragment= (IPackageFragment)fMapToPackageFragments.get(key);
if (iPackageFragment!= null && !iPackageFragment.equals(frag)){
lp= new LogicalPackage(iPackageFragment);
lp.add(frag);
//add new LogicalPackage to LogicalPackages map
fMapToLogicalPackage.put(key, lp);
//determin who to refresh
if (parent instanceof IPackageFragmentRoot){
IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
if (fInputIsProject){
postRefresh(root.getJavaProject());
} else {
postRefresh(root);
}
} else {
//@Improve: Shoud this be replaced by a refresh?
postAdd(lp, parent);
postRemove(iPackageFragment);
}
}
//if this is a new Package Fragment
else {
fMapToPackageFragments.put(key, frag);
//determin who to refresh
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
if (fInputIsProject) {
postAdd(frag, root.getJavaProject());
} else
postAdd(frag, root);
} else {
postAdd(frag, parent);
}
}
}
private void removeElement(IPackageFragment frag) {
String key= getKey(frag);
LogicalPackage lp= (LogicalPackage)fMapToLogicalPackage.get(key);
if(lp != null){
lp.remove(frag);
//if the LogicalPackage needs to revert back to a PackageFragment
//remove it from the LogicalPackages map and add the PackageFragment
//to the PackageFragment map
if (lp.getFragments().length == 1) {
IPackageFragment fragment= lp.getFragments()[0];
fMapToPackageFragments.put(key, fragment);
fMapToLogicalPackage.remove(key);
//remove the LogicalPackage frome viewer
postRemove(lp);
Object parent= getParent(fragment);
if (parent instanceof IPackageFragmentRoot) {
parent= ((IPackageFragmentRoot)parent).getJavaProject();
}
postAdd(fragment, parent);
}
} else {
//remove the fragment from the fragment map and viewer
IPackageFragment fragment= (IPackageFragment) fMapToPackageFragments.get(key);
if (fragment!= null && fragment.equals(frag)) {
fMapToPackageFragments.remove(key);
postRemove(frag);
}
}
}
}
|
33,219 |
Bug 33219 Leightweight outline no longer resizable
|
This is a regression.
|
resolved fixed
|
08a2f6e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T08:43:52Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaOutlineInformationControl.java
|
/*
* Copyright (c) 2000, 2002 IBM Corp. and others..
* All rights reserved. ? This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
?*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package org.eclipse.jdt.internal.ui.text;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlExtension;
import org.eclipse.jface.text.IInformationControlExtension2;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.util.StringMatcher;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* @author dmegert
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
public class JavaOutlineInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2 {
/**
* The NamePatternFilter selects the elements which
* match the given string patterns.
* <p>
* The following characters have special meaning:
* ? => any character
* * => any string
* </p>
*
* @since 2.0
*/
private static class NamePatternFilter extends ViewerFilter {
private String fPattern;
private StringMatcher fMatcher;
private ILabelProvider fLabelProvider;
private Viewer fViewer;
private StringMatcher getMatcher() {
return fMatcher;
}
/* (non-Javadoc)
* Method declared on ViewerFilter.
*/
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (fMatcher == null)
return true;
ILabelProvider labelProvider= getLabelProvider(viewer);
String matchName= null;
if (labelProvider != null)
matchName= ((ILabelProvider)labelProvider).getText(element);
else if (element instanceof IJavaElement)
matchName= ((IJavaElement) element).getElementName();
if (matchName != null && fMatcher.match(matchName))
return true;
return hasUnfilteredChild(viewer, element);
}
private ILabelProvider getLabelProvider(Viewer viewer) {
if (fViewer == viewer)
return fLabelProvider;
fLabelProvider= null;
IBaseLabelProvider baseLabelProvider= null;
if (viewer instanceof StructuredViewer)
baseLabelProvider= ((StructuredViewer)viewer).getLabelProvider();
if (baseLabelProvider instanceof ILabelProvider)
fLabelProvider= (ILabelProvider)baseLabelProvider;
return fLabelProvider;
}
private boolean hasUnfilteredChild(Viewer viewer, Object element) {
IJavaElement[] children;
if (element instanceof IParent) {
try {
children= ((IParent)element).getChildren();
} catch (JavaModelException ex) {
return false;
}
for (int i= 0; i < children.length; i++)
if (select(viewer, element, children[i]))
return true;
}
return false;
}
/**
* Sets the patterns to filter out for the receiver.
* <p>
* The following characters have special meaning:
* ? => any character
* * => any string
* </p>
*/
public void setPattern(String pattern) {
fPattern= pattern;
if (fPattern == null) {
fMatcher= null;
return;
}
boolean ignoreCase= pattern.toLowerCase().equals(pattern);
fMatcher= new StringMatcher(pattern, ignoreCase, false);
}
}
private static class BorderFillLayout extends Layout {
/** The border widths. */
final int fBorderSize;
/**
* Creates a fill layout with a border.
*/
public BorderFillLayout(int borderSize) {
if (borderSize < 0)
throw new IllegalArgumentException();
fBorderSize= borderSize;
}
/**
* Returns the border size.
*/
public int getBorderSize() {
return fBorderSize;
}
/*
* @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite, int, int, boolean)
*/
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
Control[] children= composite.getChildren();
Point minSize= new Point(0, 0);
if (children != null) {
for (int i= 0; i < children.length; i++) {
Point size= children[i].computeSize(wHint, hHint, flushCache);
minSize.x= Math.max(minSize.x, size.x);
minSize.y= Math.max(minSize.y, size.y);
}
}
minSize.x += fBorderSize * 2 + RIGHT_MARGIN;
minSize.y += fBorderSize * 2;
return minSize;
}
/*
* @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite, boolean)
*/
protected void layout(Composite composite, boolean flushCache) {
Control[] children= composite.getChildren();
Point minSize= new Point(composite.getClientArea().width, composite.getClientArea().height);
if (children != null) {
for (int i= 0; i < children.length; i++) {
Control child= children[i];
child.setSize(minSize.x - fBorderSize * 2, minSize.y - fBorderSize * 2);
child.setLocation(fBorderSize, fBorderSize);
}
}
}
}
/** Border thickness in pixels. */
private static final int BORDER= 1;
/** Right margin in pixels. */
private static final int RIGHT_MARGIN= 3;
/** The control's shell */
private Shell fShell;
/** The composite */
Composite fComposite;
/** The control's text widget */
private Text fFilterText;
/** The control's tree widget */
private TreeViewer fTreeViewer;
/** The control width constraint */
private int fMaxWidth= -1;
/** The control height constraint */
private int fMaxHeight= -1;
private StringMatcher fStringMatcher;
/**
* Creates a tree information control with the given shell as parent. The given
* style is applied to the tree widget.
*
* @param parent the parent shell
* @param style the additional styles for the tree widget
*/
public JavaOutlineInformationControl(Shell parent, int style) {
this(parent, SWT.NO_TRIM, style);
}
/**
* Creates a tree information control with the given shell as parent.
* No additional styles are applied.
*
* @param parent the parent shell
*/
public JavaOutlineInformationControl(Shell parent) {
this(parent, SWT.NONE);
}
/**
* Creates a tree information control with the given shell as parent. The given
* styles are applied to the shell and the tree widget.
*
* @param parent the parent shell
* @param shellStyle the additional styles for the shell
* @param treeStyle the additional styles for the tree widget
*/
public JavaOutlineInformationControl(Shell parent, int shellStyle, int treeStyle) {
fShell= new Shell(parent, SWT.NO_FOCUS | SWT.NO_TRIM | shellStyle);
Display display= fShell.getDisplay();
fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
// Composite for filter text and tree
fComposite= new Composite(fShell,SWT.RESIZE);
GridLayout layout= new GridLayout(1, false);
fComposite.setLayout(layout);
fComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createFilterText(fComposite);
createTreeViewer(fComposite, treeStyle);
int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER;
fShell.setLayout(new BorderFillLayout(border));
setInfoSystemColor();
installFilter();
}
private void createTreeViewer(Composite parent, int style) {
Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI));
GridData data= new GridData(GridData.FILL_BOTH);
tree.setLayoutData(data);
fTreeViewer= new TreeViewer(tree);
// Hide import declartions but show the container
fTreeViewer.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
return !(element instanceof IImportDeclaration);
}
});
fTreeViewer.setContentProvider(new StandardJavaElementContentProvider(true, true));
fTreeViewer.setSorter(new JavaElementSorter());
fTreeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
fTreeViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider));
fTreeViewer.getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.character == 0x1B) // ESC
dispose();
}
public void keyReleased(KeyEvent e) {
// do nothing
}
});
fTreeViewer.getTree().addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
// do nothing
}
public void widgetDefaultSelected(SelectionEvent e) {
gotoSelectedElement();
}
});
}
private Text createFilterText(Composite parent) {
fFilterText= new Text(parent, SWT.FLAT);
GridData data= new GridData();
GC gc= new GC(parent);
gc.setFont(parent.getFont());
FontMetrics fontMetrics= gc.getFontMetrics();
gc.dispose();
data.heightHint= org.eclipse.jface.dialogs.Dialog.convertHeightInCharsToPixels(fontMetrics, 1);
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
fFilterText.setLayoutData(data);
fFilterText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == 0x0D) // return
gotoSelectedElement();
if (e.keyCode == SWT.ARROW_DOWN)
fTreeViewer.getTree().setFocus();
if (e.keyCode == SWT.ARROW_UP)
fTreeViewer.getTree().setFocus();
if (e.character == 0x1B) // ESC
dispose();
}
public void keyReleased(KeyEvent e) {
// do nothing
}
});
// Horizonral separator line
Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return fFilterText;
}
private void setInfoSystemColor() {
Display display= fShell.getDisplay();
setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
private void installFilter() {
final NamePatternFilter viewerFilter= new NamePatternFilter();
fTreeViewer.addFilter(viewerFilter);
fFilterText.setText(""); //$NON-NLS-1$
fFilterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String pattern= fFilterText.getText();
if (pattern != null) {
int length= pattern.length();
if (length == 0)
pattern= null;
else if (pattern.charAt(length -1 ) != '*')
pattern= pattern + '*';
} else
pattern= null;
viewerFilter.setPattern(pattern);
fStringMatcher= viewerFilter.getMatcher();
fTreeViewer.getControl().setRedraw(false);
fTreeViewer.refresh();
fTreeViewer.expandAll();
selectFirstMatch();
fTreeViewer.getControl().setRedraw(true);
}
});
}
private void gotoSelectedElement() {
Object selectedElement= ((IStructuredSelection)fTreeViewer.getSelection()).getFirstElement();
if (selectedElement != null) {
try {
dispose();
OpenActionUtil.open(selectedElement, true);
} catch (CoreException ex) {
JavaPlugin.log(ex);
}
}
}
/**
* Selects the first element in the tree which
* matches the current filter pattern.
*/
private void selectFirstMatch() {
Tree tree= fTreeViewer.getTree();
Object element= findElement(tree.getItems());
if (element != null)
fTreeViewer.setSelection(new StructuredSelection(element), true);
else
fTreeViewer.setSelection(StructuredSelection.EMPTY);
}
private IJavaElement findElement(TreeItem[] items) {
ILabelProvider labelProvider= (ILabelProvider)fTreeViewer.getLabelProvider();
for (int i= 0; i < items.length; i++) {
IJavaElement element= (IJavaElement)items[i].getData();
if (fStringMatcher == null)
return element;
if (element != null) {
String label= labelProvider.getText(element);
if (fStringMatcher.match(label))
return element;
}
element= findElement(items[i].getItems());
if (element != null)
return element;
}
return null;
}
/*
* @see IInformationControl#setInformation(String)
*/
public void setInformation(String information) {
// this method is ignored, see IInformationControlExtension2
}
/*
* @see IInformationControlExtension2#setInput(Object)
*/
public void setInput(Object information) {
fFilterText.setText(""); //$NON-NLS-1$
if (information == null || information instanceof String) {
setInput(null);
return;
}
IJavaElement je= (IJavaElement)information;
IJavaElement sel= null;
ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null)
sel= cu;
else
sel= je.getAncestor(IJavaElement.CLASS_FILE);
fTreeViewer.setInput(sel);
fTreeViewer.setSelection(new StructuredSelection(information));
}
/*
* @see IInformationControl#setVisible(boolean)
*/
public void setVisible(boolean visible) {
fShell.setVisible(visible);
}
/*
* @see IInformationControl#dispose()
*/
public void dispose() {
if (fShell != null) {
if (!fShell.isDisposed())
fShell.dispose();
fShell= null;
fTreeViewer= null;
fComposite= null;
fFilterText= null;
}
}
/*
* @see org.eclipse.jface.text.IInformationControlExtension#hasContents()
*/
public boolean hasContents() {
return fTreeViewer != null && fTreeViewer.getInput() != null;
}
/*
* @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int)
*/
public void setSizeConstraints(int maxWidth, int maxHeight) {
fMaxWidth= maxWidth;
fMaxHeight= maxHeight;
}
/*
* @see org.eclipse.jface.text.IInformationControl#computeSizeHint()
*/
public Point computeSizeHint() {
return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
}
/*
* @see IInformationControl#setLocation(Point)
*/
public void setLocation(Point location) {
Rectangle trim= fShell.computeTrim(0, 0, 0, 0);
Point textLocation= fComposite.getLocation();
location.x += trim.x - textLocation.x;
location.y += trim.y - textLocation.y;
fShell.setLocation(location);
}
/*
* @see IInformationControl#setSize(int, int)
*/
public void setSize(int width, int height) {
fShell.setSize(width, height);
}
/*
* @see IInformationControl#addDisposeListener(DisposeListener)
*/
public void addDisposeListener(DisposeListener listener) {
fShell.addDisposeListener(listener);
}
/*
* @see IInformationControl#removeDisposeListener(DisposeListener)
*/
public void removeDisposeListener(DisposeListener listener) {
fShell.removeDisposeListener(listener);
}
/*
* @see IInformationControl#setForegroundColor(Color)
*/
public void setForegroundColor(Color foreground) {
fTreeViewer.getTree().setForeground(foreground);
fFilterText.setForeground(foreground);
fComposite.setForeground(foreground);
}
/*
* @see IInformationControl#setBackgroundColor(Color)
*/
public void setBackgroundColor(Color background) {
fTreeViewer.getTree().setBackground(background);
fFilterText.setBackground(background);
fComposite.setBackground(background);
}
/*
* @see IInformationControl#isFocusControl()
*/
public boolean isFocusControl() {
return fShell.isFocusControl();
}
/*
* @see IInformationControl#setFocus()
*/
public void setFocus() {
fShell.forceFocus();
fFilterText.setFocus();
}
/*
* @see IInformationControl#addFocusListener(FocusListener)
*/
public void addFocusListener(FocusListener listener) {
fShell.addFocusListener(listener);
}
/*
* @see IInformationControl#removeFocusListener(FocusListener)
*/
public void removeFocusListener(FocusListener listener) {
fShell.removeFocusListener(listener);
}
}
|
32,935 |
Bug 32935 Java Browsing Members view does not update on visibility change
|
Build 2.1 RC1 1. Open Java Browsing perspective 2. Open an existing CU 3. Add public method t() {} 4. Change public to protected (or remove public) ==> t in Members view does not update
|
resolved fixed
|
661597b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T08:44:57Z | 2003-02-25T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2003.
* All Rights Reserved.
*/
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.IMember;
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.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
class JavaBrowsingContentProvider extends StandardJavaElementContentProvider implements IElementChangedListener {
private StructuredViewer fViewer;
private Object fInput;
private JavaBrowsingPart fBrowsingPart;
public JavaBrowsingContentProvider(boolean provideMembers, JavaBrowsingPart browsingPart) {
super(provideMembers, reconcileJavaViews());
fBrowsingPart= browsingPart;
fViewer= fBrowsingPart.getViewer();
JavaCore.addElementChangedListener(this);
}
private static boolean reconcileJavaViews() {
return PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
}
public Object[] getChildren(Object element) {
if (!exists(element))
return NO_CHILDREN;
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;
}
}
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
ISourceReference[] sourceRefs;
if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
sourceRefs= fragment.getCompilationUnits();
if (getProvideWorkingCopy()) {
for (int i= 0; i < sourceRefs.length; i++) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)sourceRefs[i]);
if (wc != null)
sourceRefs[i]= (ICompilationUnit)wc;
}
}
}
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 (getProvideWorkingCopy()) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)parent);
if (wc != null) {
parent= (IParent)wc;
IMember wcType= EditorUtility.getWorkingCopy(type);
if (wcType != null)
type= (IType)wcType;
}
}
}
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= (IPackageFragmentRoot)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(((IWorkingCopy)element).getOriginal((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 (kind == IJavaElementDelta.CHANGED && ((flags & IJavaElementDelta.F_FINE_GRAINED) == 0)) {
if (fBrowsingPart.isValidElement(element)) {
postRefresh(element);
}
}
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) {
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((IJavaElement)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((IJavaElement)element);
ctrl.setRedraw(true);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fBrowsingPart.setProcessSelectionEvents(false);
try {
Display currentDisplay= Display.getCurrent();
if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()))
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;
}
}
|
32,469 |
Bug 32469 disabled breakpoints still rendered as enabled
|
20030221 disable a breakpoint - icon does not change but the breakpoint is disabled major - renders the important feature not very useful
|
resolved fixed
|
29ac342
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T08:59:45Z | 2003-02-21T12:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaMarkerAnnotation.java
|
/**********************************************************************
Copyright (c) 2000, 2003 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.Iterator;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.text.Assert;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugModelPresentation;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.core.Util;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnotation {
private static final int NO_IMAGE= 0;
private static final int ORIGINAL_MARKER_IMAGE= 1;
private static final int QUICKFIX_IMAGE= 2;
private static final int QUICKFIX_ERROR_IMAGE= 3;
private static final int OVERLAY_IMAGE= 4;
private static final int GRAY_IMAGE= 5;
private static final int BREAKPOINT_IMAGE= 6;
private static Image fgQuickFixImage;
private static Image fgQuickFixErrorImage;
private static ImageRegistry fgGrayMarkersImageRegistry;
private IDebugModelPresentation fPresentation;
private IJavaAnnotation fOverlay;
private boolean fNotRelevant= false;
private AnnotationType fType;
private int fImageType;
private boolean fQuickFixIconEnabled;
public JavaMarkerAnnotation(IMarker marker) {
super(marker);
}
/*
* @see MarkerAnnotation#getUnknownImageName(IMarker)
*/
protected String getUnknownImageName(IMarker marker) {
return JavaPluginImages.IMG_OBJS_GHOST;
}
/**
* Initializes the annotation's icon representation and its drawing layer
* based upon the properties of the underlying marker.
*/
protected void initialize() {
fQuickFixIconEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
fImageType= NO_IMAGE;
IMarker marker= getMarker();
if (MarkerUtilities.isMarkerType(marker, IBreakpoint.BREAKPOINT_MARKER)) {
if (fPresentation == null)
fPresentation= DebugUITools.newDebugModelPresentation();
setLayer(4);
fImageType= BREAKPOINT_IMAGE;
fType= AnnotationType.UNKNOWN;
} else {
fType= AnnotationType.UNKNOWN;
try {
if (marker.isSubtypeOf(IMarker.PROBLEM)) {
int severity= marker.getAttribute(IMarker.SEVERITY, -1);
switch (severity) {
case IMarker.SEVERITY_ERROR:
fType= AnnotationType.ERROR;
break;
case IMarker.SEVERITY_WARNING:
fType= AnnotationType.WARNING;
break;
}
} else if (marker.isSubtypeOf(IMarker.TASK))
fType= AnnotationType.TASK;
else if (marker.isSubtypeOf(SearchUI.SEARCH_MARKER))
fType= AnnotationType.SEARCH;
else if (marker.isSubtypeOf(IMarker.BOOKMARK))
fType= AnnotationType.BOOKMARK;
} catch(CoreException e) {
JavaPlugin.log(e);
}
super.initialize();
}
}
private boolean mustShowQuickFixIcon() {
return fQuickFixIconEnabled && JavaCorrectionProcessor.hasCorrections(getMarker());
}
private Image getQuickFixImage() {
if (fgQuickFixImage == null)
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
return fgQuickFixImage;
}
private Image getQuickFixErrorImage() {
if (fgQuickFixErrorImage == null)
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
return fgQuickFixErrorImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getMessage() {
IMarker marker= getMarker();
if (marker == null)
return ""; //$NON-NLS-1$
else
return marker.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
}
/*
* @see IJavaAnnotation#isTemporary()
*/
public boolean isTemporary() {
return false;
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
if (isProblem())
return Util.getProblemArgumentsFromMarker(getMarker().getAttribute(IJavaModelMarker.ARGUMENTS, "")); //$NON-NLS-1$
return null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
if (isProblem())
return getMarker().getAttribute(IJavaModelMarker.ID, -1);
return -1;
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
return fType == AnnotationType.WARNING || fType == AnnotationType.ERROR;
}
/*
* @see IJavaAnnotation#isRelevant()
*/
public boolean isRelevant() {
return !fNotRelevant;
}
/**
* Overlays this annotation with the given javaAnnotation.
*
* @param javaAnnotation annotation that is overlaid by this annotation
*/
public void setOverlay(IJavaAnnotation javaAnnotation) {
if (fOverlay != null)
fOverlay.removeOverlaid(this);
fOverlay= javaAnnotation;
fNotRelevant= (fNotRelevant || fOverlay != null);
if (javaAnnotation != null)
javaAnnotation.addOverlaid(this);
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return fOverlay != null;
}
/*
* @see MarkerAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
if (fImageType == BREAKPOINT_IMAGE) {
Image result= super.getImage(display);
if (result == null) {
result= fPresentation.getImage(getMarker());
setImage(result);
}
return result;
}
int newImageType= NO_IMAGE;
if (hasOverlay())
newImageType= OVERLAY_IMAGE;
else if (isRelevant()) {
if (mustShowQuickFixIcon()) {
if (fType == AnnotationType.ERROR)
newImageType= QUICKFIX_ERROR_IMAGE;
else
newImageType= QUICKFIX_IMAGE;
} else
newImageType= ORIGINAL_MARKER_IMAGE;
} else
newImageType= GRAY_IMAGE;
if (fImageType == newImageType && newImageType != OVERLAY_IMAGE)
// Nothing changed - simply return the current image
return super.getImage(display);
Image newImage= null;
switch (newImageType) {
case ORIGINAL_MARKER_IMAGE:
newImage= null;
break;
case OVERLAY_IMAGE:
newImage= fOverlay.getImage(display);
break;
case QUICKFIX_IMAGE:
newImage= getQuickFixImage();
break;
case QUICKFIX_ERROR_IMAGE:
newImage= getQuickFixErrorImage();
break;
case GRAY_IMAGE:
if (fImageType != ORIGINAL_MARKER_IMAGE)
setImage(null);
Image originalImage= super.getImage(display);
if (originalImage != null) {
ImageRegistry imageRegistry= getGrayMarkerImageRegistry(display);
if (imageRegistry != null) {
String key= Integer.toString(originalImage.hashCode());
Image grayImage= imageRegistry.get(key);
if (grayImage == null) {
grayImage= new Image(display, originalImage, SWT.IMAGE_GRAY);
imageRegistry.put(key, grayImage);
}
newImage= grayImage;
}
}
break;
default:
Assert.isLegal(false);
}
fImageType= newImageType;
setImage(newImage);
return super.getImage(display);
}
private ImageRegistry getGrayMarkerImageRegistry(Display display) {
if (fgGrayMarkersImageRegistry == null)
fgGrayMarkersImageRegistry= new ImageRegistry(display);
return fgGrayMarkersImageRegistry;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
// not supported
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
// not supported
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
// not supported
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getAnnotationType()
*/
public AnnotationType getAnnotationType() {
return fType;
}
}
|
31,662 |
Bug 31662 NPE in CompilationUnitDocumentProvider$CompilationUnitAnnotationModel
|
I got two the same NPE (yesterday and this morning). One in the log file, one time in the console. That happened when I started my test runtime workbench. From the log: !ENTRY org.eclipse.core.resources 4 2 Feb 11, 2003 16:09:02.16 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.resources". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$CompilationUnitAnnotationModel.removeMarkerOver lays(CompilationUnitDocumentProvider.java:484) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$CompilationUnitAnnotationModel.endReporting(Com pilationUnitDocumentProvider.java:471) at org.eclipse.jdt.internal.core.WorkingCopy.reconcile(WorkingCopy.java:454) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$CompilationUnitAnnotationModel.update(Compilati onUnitDocumentProvider.java:390) at org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel$ResourceDeltaVisitor.visit(ResourceMarkerAnnotationModel.java: 68) at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:71) at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:79) at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:79) at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:79) at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:52) at org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel$ResourceChangeListener.resourceChanged(ResourceMarkerAnnotatio nModel.java:52) at org.eclipse.core.internal.events.NotificationManager$1.run(NotificationManager.java:137) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:152) at org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:67) at org.eclipse.core.internal.resources.Workspace.broadcastChanges(Workspace.java:161) at org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:892) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1593) at org.eclipse.debug.core.model.Breakpoint.setAttributes(Breakpoint.java:218) at org.eclipse.jdt.internal.debug.core.breakpoints.JavaBreakpoint.configureAtStartup(JavaBreakpoint.java:776) at org.eclipse.jdt.internal.debug.core.breakpoints.JavaBreakpoint.setMarker(JavaBreakpoint.java:154) at org.eclipse.debug.internal.core.BreakpointManager.createBreakpoint(BreakpointManager.java:382) at org.eclipse.debug.internal.core.BreakpointManager.loadBreakpoints(BreakpointManager.java:133) at org.eclipse.debug.internal.core.BreakpointManager.initializeBreakpoints(BreakpointManager.java:285) at org.eclipse.debug.internal.core.BreakpointManager.getBreakpoints0(BreakpointManager.java:256) at org.eclipse.debug.internal.core.BreakpointManager.getBreakpoint(BreakpointManager.java:235) at org.eclipse.debug.internal.ui.DelegatingModelPresentation.getConfiguredPresentation(DelegatingModelPresentation.java:2 29) at org.eclipse.debug.internal.ui.DelegatingModelPresentation.getImage(DelegatingModelPresentation.java:103) at org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation.initialize(JavaMarkerAnnotation.java:97) at org.eclipse.ui.texteditor.MarkerAnnotation.<init>(MarkerAnnotation.java:111) at org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation.<init>(JavaMarkerAnnotation.java:72) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$CompilationUnitAnnotationModel.createMarkerAnno tation(CompilationUnitDocumentProvider.java:369) at org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel.addMarkerAnnotation(AbstractMarkerAnnotationModel.java:215) at org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel.catchupWithMarkers(AbstractMarkerAnnotationModel.java:394) at org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel.connected(AbstractMarkerAnnotationModel.java:228) at org.eclipse.jface.text.source.AnnotationModel.connect(AnnotationModel.java:139) at org.eclipse.jface.text.source.VisualAnnotationModel.connect(VisualAnnotationModel.java:70) at org.eclipse.jface.text.source.SourceViewer.setDocument(SourceViewer.java:364) at org.eclipse.jface.text.source.SourceViewer.setDocument(SourceViewer.java:337) at org.eclipse.ui.texteditor.AbstractTextEditor.initializeSourceViewer(AbstractTextEditor.java:2179) at org.eclipse.ui.texteditor.AbstractTextEditor.createPartControl(AbstractTextEditor.java:1980) at org.eclipse.ui.texteditor.StatusTextEditor.createPartControl(StatusTextEditor.java:53) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.createPartControl(JavaEditor.java:2030) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.createPartControl(CompilationUnitEditor.java:978) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:138) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.PartPane.createChildControl(PartPane.java:134) at org.eclipse.ui.internal.PartPane.createControl(PartPane.java:183) at org.eclipse.ui.internal.EditorWorkbook.createPage(EditorWorkbook.java:393) at org.eclipse.ui.internal.EditorWorkbook.createControl(EditorWorkbook.java:276) at org.eclipse.ui.internal.PartSashContainer.createControl(PartSashContainer.java:191) at org.eclipse.ui.internal.EditorArea.createControl(EditorArea.java:323) at org.eclipse.ui.internal.PartSashContainer.createControl(PartSashContainer.java:191) at org.eclipse.ui.internal.PerspectivePresentation.activate(PerspectivePresentation.java:94) at org.eclipse.ui.internal.Perspective.onActivate(Perspective.java:717) at org.eclipse.ui.internal.WorkbenchPage.onActivate(WorkbenchPage.java:1767) at org.eclipse.ui.internal.WorkbenchWindow$7.run(WorkbenchWindow.java:1394) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.WorkbenchWindow.setActivePage(WorkbenchWindow.java:1381) at org.eclipse.ui.internal.WorkbenchWindow.restoreState(WorkbenchWindow.java:1262) at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1150) at org.eclipse.ui.internal.Workbench.access$9(Workbench.java:1110) at org.eclipse.ui.internal.Workbench$10.run(Workbench.java:1028) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.Workbench.openPreviousWorkbenchState(Workbench.java:980) at org.eclipse.ui.internal.Workbench.init(Workbench.java:725) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1260) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) From the console: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$CompilationUnitAnnotationModel.removeMarkerOverlays(CompilationUnitDocumentProvider.java:484) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$CompilationUnitAnnotationModel.endReporting(CompilationUnitDocumentProvider.java:471) at org.eclipse.jdt.internal.core.WorkingCopy.reconcile(WorkingCopy.java:454) at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:73) at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.initialReconcile(JavaReconcilingStrategy.java:127) at org.eclipse.jface.text.reconciler.MonoReconciler.initialProcess(MonoReconciler.java:104) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:155)
|
resolved fixed
|
31153dd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T13:41:34Z | 2003-02-12T14:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.editors.text.FileDocumentProvider;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.IBufferFactory;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IOpenable;
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.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIStatus;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension;
public class CompilationUnitDocumentProvider extends FileDocumentProvider implements IWorkingCopyManager {
/**
* Here for visibility issues only.
*/
protected class _FileSynchronizer extends FileSynchronizer {
public _FileSynchronizer(IFileEditorInput fileEditorInput) {
super(fileEditorInput);
}
};
/**
* Bundle of all required informations to allow working copy management.
*/
protected class CompilationUnitInfo extends FileInfo {
ICompilationUnit fCopy;
public CompilationUnitInfo(IDocument document, IAnnotationModel model, _FileSynchronizer fileSynchronizer, ICompilationUnit copy) {
super(document, model, fileSynchronizer);
fCopy= copy;
}
public void setModificationStamp(long timeStamp) {
fModificationStamp= timeStamp;
}
};
/**
* Annotation representating an <code>IProblem</code>.
*/
static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation {
private static Image fgQuickFixImage;
private static Image fgQuickFixErrorImage;
private static boolean fgQuickFixImagesInitialized= false;
private List fOverlaids;
private IProblem fProblem;
private Image fImage;
private boolean fQuickFixImagesInitialized= false;
private AnnotationType fType;
public ProblemAnnotation(IProblem problem) {
fProblem= problem;
setLayer(MarkerAnnotation.PROBLEM_LAYER + 1);
if (IProblem.Task == fProblem.getID())
fType= AnnotationType.TASK;
else if (fProblem.isWarning())
fType= AnnotationType.WARNING;
else
fType= AnnotationType.ERROR;
}
private void initializeImages() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
if (!fQuickFixImagesInitialized) {
if (indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(fProblem.getID())) {
if (!fgQuickFixImagesInitialized) {
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
fgQuickFixImagesInitialized= true;
}
if (fType == AnnotationType.ERROR)
fImage= fgQuickFixErrorImage;
else
fImage= fgQuickFixImage;
}
fQuickFixImagesInitialized= true;
}
}
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
/*
* @see IJavaAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
initializeImages();
return fImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getMessage() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#isTemporary()
*/
public boolean isTemporary() {
return true;
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
return isProblem() ? fProblem.getArguments() : null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
return isProblem() ? fProblem.getID() : -1;
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
return fType == AnnotationType.WARNING || fType == AnnotationType.ERROR;
}
/*
* @see IJavaAnnotation#isRelevant()
*/
public boolean isRelevant() {
return true;
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
if (fOverlaids == null)
fOverlaids= new ArrayList(1);
fOverlaids.add(annotation);
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
if (fOverlaids != null) {
fOverlaids.remove(annotation);
if (fOverlaids.size() == 0)
fOverlaids= null;
}
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
if (fOverlaids != null)
return fOverlaids.iterator();
return null;
}
public AnnotationType getAnnotationType() {
return fType;
}
};
/**
* Internal structure for mapping positions to some value.
* The reason for this specific structure is that positions can
* change over time. Thus a lookup is based on value and not
* on hash value.
*/
protected static class ReverseMap {
static class Entry {
Position fPosition;
Object fValue;
};
private List fList= new ArrayList(2);
private int fAnchor= 0;
public ReverseMap() {
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private int getIndex(Position position) {
Entry entry;
int length= fList.size();
for (int i= 0; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position))
return i;
}
return -1;
}
public void put(Position position, Object value) {
int index= getIndex(position);
if (index == -1) {
Entry entry= new Entry();
entry.fPosition= position;
entry.fValue= value;
fList.add(entry);
} else {
Entry entry= (Entry) fList.get(index);
entry.fValue= value;
}
}
public void remove(Position position) {
int index= getIndex(position);
if (index > -1)
fList.remove(index);
}
public void clear() {
fList.clear();
}
};
/**
* Annotation model dealing with java marker annotations and temporary problems.
* Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
* activated.
*/
protected class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
private IFileEditorInput fInput;
private List fCollectedProblems;
private List fGeneratedAnnotations;
private IProgressMonitor fProgressMonitor;
private boolean fIsActive= false;
private ReverseMap fReverseMap= new ReverseMap();
private List fPreviouslyOverlaid= null;
private List fCurrentlyOverlaid= new ArrayList();
public CompilationUnitAnnotationModel(IFileEditorInput input) {
super(input.getFile());
fInput= input;
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
return new JavaMarkerAnnotation(marker);
}
protected Position createPositionFromProblem(IProblem problem) {
int start= problem.getSourceStart();
if (start < 0)
return null;
int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
if (length < 0)
return null;
return new Position(start, length);
}
protected void update(IMarkerDelta[] markerDeltas) {
super.update(markerDeltas);
if (markerDeltas != null && markerDeltas.length > 0) {
try {
ICompilationUnit workingCopy = getWorkingCopy(fInput);
if (workingCopy != null)
workingCopy.reconcile(true, null);
} catch (JavaModelException ex) {
handleCoreException(ex, ex.getMessage());
}
}
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
ICompilationUnit unit= getWorkingCopy(fInput);
try {
if (unit != null && unit.getJavaProject().isOnClasspath(unit))
fCollectedProblems= new ArrayList();
else
fCollectedProblems= null;
} catch (JavaModelException e) {
fCollectedProblems= null;
}
}
/*
* @see IProblemRequestor#acceptProblem(IProblem)
*/
public void acceptProblem(IProblem problem) {
if (isActive())
fCollectedProblems.add(problem);
}
/*
* @see IProblemRequestor#endReporting()
*/
public void endReporting() {
if (!isActive())
return;
if (fProgressMonitor != null && fProgressMonitor.isCanceled())
return;
boolean isCanceled= false;
boolean temporaryProblemsChanged= false;
fPreviouslyOverlaid= fCurrentlyOverlaid;
fCurrentlyOverlaid= new ArrayList();
synchronized (fAnnotations) {
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) {
ProblemAnnotation annotation= new ProblemAnnotation(problem);
overlayMarkers(position, annotation);
fGeneratedAnnotations.add(annotation);
addAnnotation(annotation, position, false);
temporaryProblemsChanged= true;
}
}
fCollectedProblems.clear();
}
removeMarkerOverlays(isCanceled);
fPreviouslyOverlaid.clear();
fPreviouslyOverlaid= null;
}
if (temporaryProblemsChanged)
fireModelChanged(new CompilationUnitAnnotationModelEvent(this, getResource(), false));
}
private void removeMarkerOverlays(boolean isCanceled) {
if (isCanceled) {
fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
} else {
Iterator e= fPreviouslyOverlaid.iterator();
while (e.hasNext()) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
annotation.setOverlay(null);
}
}
}
/**
* Overlays value with problem annotation.
* @param problemAnnotation
*/
private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
if (value instanceof JavaMarkerAnnotation) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
if (annotation.isProblem()) {
annotation.setOverlay(problemAnnotation);
fPreviouslyOverlaid.remove(annotation);
fCurrentlyOverlaid.add(annotation);
}
}
}
private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
Object value= getAnnotations(position);
if (value instanceof List) {
List list= (List) value;
for (Iterator e = list.iterator(); e.hasNext();)
setOverlay(e.next(), problemAnnotation);
} else {
setOverlay(value, problemAnnotation);
}
}
/**
* Tells this annotation model to collect temporary problems from now on.
*/
private void startCollectingProblems() {
fCollectedProblems= new ArrayList();
fGeneratedAnnotations= new ArrayList();
}
/**
* Tells this annotation model to no longer collect temporary problems.
*/
private void stopCollectingProblems() {
if (fGeneratedAnnotations != null) {
removeAnnotations(fGeneratedAnnotations, true, true);
fGeneratedAnnotations.clear();
}
fCollectedProblems= null;
fGeneratedAnnotations= null;
}
/*
* @see AnnotationModel#fireModelChanged()
*/
protected void fireModelChanged() {
fireModelChanged(new CompilationUnitAnnotationModelEvent(this, getResource(), true));
}
/*
* @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) {
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);
}
};
/**
* Creates <code>IBuffer</code>s based on documents.
*/
protected class BufferFactory implements IBufferFactory {
private IDocument internalGetDocument(IFileEditorInput input) throws CoreException {
IDocument document= getDocument(input);
if (document != null)
return document;
return CompilationUnitDocumentProvider.this.createDocument(input);
}
public IBuffer createBuffer(IOpenable owner) {
if (owner instanceof ICompilationUnit) {
ICompilationUnit unit= (ICompilationUnit) owner;
ICompilationUnit original= (ICompilationUnit) unit.getOriginalElement();
IResource resource= original.getResource();
if (resource instanceof IFile) {
IFileEditorInput providerKey= new FileEditorInput((IFile) resource);
IDocument document= null;
IStatus status= null;
try {
document= internalGetDocument(providerKey);
} catch (CoreException x) {
status= x.getStatus();
document= new Document();
initializeDocument(document);
}
DocumentAdapter adapter= new DocumentAdapter(unit, document, new DefaultLineTracker(), CompilationUnitDocumentProvider.this, providerKey);
adapter.setStatus(status);
return adapter;
}
}
return DocumentAdapter.NULL;
}
};
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);
}
};
/**
* Document that can also be used by a background reconciler.
*/
protected static class PartiallySynchronizedDocument extends Document {
/*
* @see IDocumentExtension#startSequentialRewrite(boolean)
*/
synchronized public void startSequentialRewrite(boolean normalized) {
super.startSequentialRewrite(normalized);
}
/*
* @see IDocumentExtension#stopSequentialRewrite()
*/
synchronized public void stopSequentialRewrite() {
super.stopSequentialRewrite();
}
/*
* @see IDocument#get()
*/
synchronized public String get() {
return super.get();
}
/*
* @see IDocument#get(int, int)
*/
synchronized public String get(int offset, int length) throws BadLocationException {
return super.get(offset, length);
}
/*
* @see IDocument#getChar(int)
*/
synchronized public char getChar(int offset) throws BadLocationException {
return super.getChar(offset);
}
/*
* @see IDocument#replace(int, int, String)
*/
synchronized public void replace(int offset, int length, String text) throws BadLocationException {
super.replace(offset, length, text);
}
/*
* @see IDocument#set(String)
*/
synchronized public void set(String text) {
super.set(text);
}
};
/* Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
/** The buffer factory */
private IBufferFactory fBufferFactory= new BufferFactory();
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave= false;
/** The save policy used by this provider */
private ISavePolicy fSavePolicy;
/** Internal property changed listener */
private IPropertyChangeListener fPropertyListener;
/** annotation model listener added to all created CU annotation models */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
/**
* Constructor
*/
public CompilationUnitDocumentProvider() {
fPropertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
enableHandlingTemporaryProblems();
}
};
fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
}
/**
* Sets the document provider's save policy.
*/
public void setSavePolicy(ISavePolicy savePolicy) {
fSavePolicy= savePolicy;
}
/**
* 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;
}
/**
* Creates a line tracker working with the same line delimiters as the document
* of the given element. Assumes the element to be managed by this document provider.
*
* @param element the element serving as blue print
* @return a line tracker based on the same line delimiters as the element's document
*/
public ILineTracker createLineTracker(Object element) {
return new DefaultLineTracker();
}
/*
* @see AbstractDocumentProvider#createElementInfo(Object)
*/
protected ElementInfo createElementInfo(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
return super.createElementInfo(element);
IFileEditorInput input= (IFileEditorInput) element;
ICompilationUnit original= createCompilationUnit(input.getFile());
if (original != null) {
try {
try {
refreshFile(input.getFile());
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
}
IAnnotationModel m= createCompilationUnitAnnotationModel(input);
IProblemRequestor r= m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
ICompilationUnit c= (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r);
DocumentAdapter a= null;
try {
a= (DocumentAdapter) c.getBuffer();
} catch (ClassCastException x) {
IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IJavaStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
throw new CoreException(status);
}
_FileSynchronizer f= new _FileSynchronizer(input);
f.install();
CompilationUnitInfo info= new CompilationUnitInfo(a.getDocument(), m, f, c);
info.setModificationStamp(computeModificationStamp(input.getFile()));
info.fStatus= a.getStatus();
info.fEncoding= getPersistedEncoding(input);
if (r instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) r;
extension.setIsActive(isHandlingTemporaryProblems());
}
m.addAnnotationModelListener(fGlobalAnnotationModelListener);
return info;
} catch (JavaModelException x) {
throw new CoreException(x.getStatus());
}
} else {
return super.createElementInfo(element);
}
}
/*
* @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
*/
protected void disposeElementInfo(Object element, ElementInfo info) {
if (info instanceof CompilationUnitInfo) {
CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
cuInfo.fCopy.destroy();
cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
}
super.disposeElementInfo(element, info);
}
/*
* @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
*/
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
// update structure, assumes lock on info.fCopy
info.fCopy.reconcile();
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource == null) {
// underlying resource has been deleted, just recreate file, ignore the rest
super.doSaveDocument(monitor, element, document, overwrite);
return;
}
if (resource != null && !overwrite)
checkSynchronizationState(info.fModificationStamp, resource);
if (fSavePolicy != null)
fSavePolicy.preSave(info.fCopy);
// inform about the upcoming content change
fireElementStateChanging(element);
try {
fIsAboutToSave= true;
// commit working copy
info.fCopy.commit(overwrite, monitor);
} catch (CoreException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} catch (RuntimeException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} finally {
fIsAboutToSave= false;
}
// If here, the dirty state of the editor will change to "not dirty".
// Thus, the state changing flag will be reset.
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
model.updateMarkers(info.fDocument);
if (resource != null)
info.setModificationStamp(computeModificationStamp(resource));
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(original);
if (unit != null) {
IResource r= unit.getResource();
IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
if (markers != null && markers.length > 0) {
for (int i= 0; i < markers.length; i++)
model.updateMarker(markers[i], info.fDocument, null);
}
}
}
} else {
super.doSaveDocument(monitor, element, document, overwrite);
}
}
/**
* Replaces createAnnotionModel of the super class.
*/
protected IAnnotationModel createCompilationUnitAnnotationModel(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE_TYPE, "", null)); //$NON-NLS-1$
IFileEditorInput input= (IFileEditorInput) element;
return new CompilationUnitAnnotationModel(input);
}
protected void initializeDocument(IDocument document) {
if (document != null) {
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
IDocumentPartitioner partitioner= tools.createDocumentPartitioner();
document.setDocumentPartitioner(partitioner);
partitioner.connect(document);
}
}
/*
* @see AbstractDocumentProvider#createDocument(Object)
*/
protected IDocument createDocument(Object element) throws CoreException {
if (element instanceof IEditorInput) {
Document document= new PartiallySynchronizedDocument();
if (setDocumentContent(document, (IEditorInput) element, getEncoding(element))) {
initializeDocument(document);
return document;
}
}
return null;
}
/*
* @see AbstractDocumentProvider#resetDocument(Object)
*/
public void resetDocument(Object element) throws CoreException {
if (element == null)
return;
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
IDocument document;
IStatus status= null;
try {
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource instanceof IFile) {
IFile file= (IFile) resource;
try {
refreshFile(file);
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
}
IFileEditorInput input= new FileEditorInput(file);
document= super.createDocument(input);
} else {
document= new Document();
}
} catch (CoreException x) {
document= new Document();
status= x.getStatus();
}
fireElementContentAboutToBeReplaced(element);
removeUnchangedElementListeners(element, info);
info.fDocument.set(document.get());
info.fCanBeSaved= false;
info.fStatus= status;
addUnchangedElementListeners(element, info);
fireElementContentReplaced(element);
fireElementDirtyStateChanged(element, false);
} else {
super.resetDocument(element);
}
}
/**
* Saves the content of the given document to the given element.
* This is only performed when this provider initiated the save.
*
* @param monitor the progress monitor
* @param element the element to which to save
* @param document the document to save
* @param overwrite <code>true</code> if the save should be enforced
*/
public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
if (!fIsAboutToSave)
return;
if (element instanceof IFileEditorInput) {
IFileEditorInput input= (IFileEditorInput) element;
try {
String encoding= getEncoding(element);
if (encoding == null)
encoding= ResourcesPlugin.getEncoding();
InputStream stream= new ByteArrayInputStream(document.get().getBytes(encoding));
IFile file= input.getFile();
file.setContents(stream, overwrite, true, monitor);
} catch (IOException x) {
IStatus s= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.OK, x.getMessage(), x);
throw new CoreException(s);
}
}
}
/**
* Returns the underlying resource for the given element.
*
* @param the element
* @return the underlying resource of the given element
*/
public IResource getUnderlyingResource(Object element) {
if (element instanceof IFileEditorInput) {
IFileEditorInput input= (IFileEditorInput) element;
return input.getFile();
}
return null;
}
/*
* @see IWorkingCopyManager#connect(IEditorInput)
*/
public void connect(IEditorInput input) throws CoreException {
super.connect(input);
}
/*
* @see IWorkingCopyManager#disconnect(IEditorInput)
*/
public void disconnect(IEditorInput input) {
super.disconnect(input);
}
/*
* @see IWorkingCopyManager#getWorkingCopy(Object)
*/
public ICompilationUnit getWorkingCopy(IEditorInput element) {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
return info.fCopy;
}
return null;
}
/**
* Gets the BufferFactory.
*/
public IBufferFactory getBufferFactory() {
return fBufferFactory;
}
public void shutdown() {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
Iterator e= getConnectedElements();
while (e.hasNext())
disconnect(e.next());
}
/**
* Returns the preference whether handling temporary problems is enabled.
*/
protected boolean isHandlingTemporaryProblems() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
}
/**
* Switches the state of problem acceptance according to the value in the preference store.
*/
protected void enableHandlingTemporaryProblems() {
boolean enable= isHandlingTemporaryProblems();
for (Iterator iter= getConnectedElements(); iter.hasNext();) {
ElementInfo element= getElementInfo(iter.next());
if (element instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo)element;
if (info.fModel instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
extension.setIsActive(enable);
}
}
}
}
/**
* Adds a listener that reports changes from all compilation unit annotation models.
*/
public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.addListener(listener);
}
/**
* Removes the listener.
*/
public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.removeListener(listener);
}
}
|
32,680 |
Bug 32680 Print margin is in wrong location
|
Eclipse 2.1 (RC1) After changing my font to "Courier New", then turning on the Print Margin, I had to realize that it was located in the wrong place (off by some characters)
|
resolved fixed
|
8bc835b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T16:52:24Z | 2003-02-24T15:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.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.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.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
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.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
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.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.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.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.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider {
/**
* "Smart" runnable for updating the outline page's selection.
*/
class OutlinePageSelectionUpdater implements Runnable {
/** Has the runnable already been posted? */
private boolean fPosted= false;
public OutlinePageSelectionUpdater() {
}
/*
* @see Runnable#run()
*/
public void run() {
synchronizeOutlinePageSelection();
fPosted= false;
}
/**
* Posts this runnable into the event queue.
*/
public void post() {
if (fPosted)
return;
Shell shell= getSite().getShell();
if (shell != null & !shell.isDisposed()) {
fPosted= true;
shell.getDisplay().asyncExec(this);
}
}
};
class SelectionChangedListener implements ISelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** 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);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
}
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= Action.findModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
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();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// 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;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
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();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
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 && !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();
}
});
}
}
}
/*
* @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() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
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
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
final IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
final String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
// with information provider
IInformationProvider informationProvider= new IInformationProvider() {
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int offset) {
return hoverRegion;
}
/*
* @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 hoverInfo;
}
};
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
};
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
};
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
};
/** Preference key for showing the line number ruler */
protected final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
protected final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** 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 highlighting current line */
protected final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
protected final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
protected final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
protected final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
protected final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for error indication */
protected final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION;
/** Preference key for error color */
protected final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
/** Preference key for warning indication */
protected final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION;
/** Preference key for warning color */
protected final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
/** Preference key for task indication */
protected final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION;
/** Preference key for task color */
protected final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
/** Preference key for bookmark indication */
protected final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
/** Preference key for bookmark color */
protected final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
/** Preference key for search result indication */
protected final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
/** Preference key for search result color */
protected final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
/** Preference key for unknown annotation indication */
protected final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
/** Preference key for unknown annotation color */
protected final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
/** Preference key for shwoing the overview ruler */
protected final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for error indication in overview ruler */
protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for warning indication in overview ruler */
protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for task indication in overview ruler */
protected final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for bookmark indication in overview ruler */
protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for search result indication in overview ruler */
protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for unknown annotation indication in overview ruler */
protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
/** 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;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/** The selection changed listener */
protected ISelectionChangedListener fSelectionChangedListener= new SelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The outline page selection updater */
private OutlinePageSelectionUpdater fUpdater;
/** Indicates whether this editor should react on outline page selection changes */
private int fIgnoreOutlinePageSelection;
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** The annotation access */
protected IAnnotationAccess fAnnotationAccess= new AnnotationAccess();
/** The overview ruler */
protected OverviewRuler isOverviewRulerVisible;
/** The source viewer decoration support */
protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
/** The overview ruler */
protected OverviewRuler fOverviewRuler;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset
*
* @param offset the offset inside of the requested 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));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
fUpdater= new OutlinePageSelectionUpdater();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISharedTextColors sharedColors= JavaPlugin.getDefault().getJavaTextTools().getColorManager();
fOverviewRuler= new OverviewRuler(fAnnotationAccess, VERTICAL_RULER_WIDTH, sharedColors);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.WARNING);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.ERROR);
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, fOverviewRuler, 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);
fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, fOverviewRuler, fAnnotationAccess, sharedColors);
configureSourceViewerDecorationSupport();
return viewer;
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
page.addSelectionChangedListener(fSelectionChangedListener);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null || fOutlinePage == null)
return;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return;
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);
if (element instanceof ISourceReference) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
/*
* 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;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
textWidget.setRedraw(false);
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
} finally {
if (textWidget != null)
textWidget.setRedraw(true);
}
} 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) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select(reference);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
}
public synchronized void editingScriptStarted() {
++ fIgnoreOutlinePageSelection;
}
public synchronized void editingScriptEnded() {
-- fIgnoreOutlinePageSelection;
}
public synchronized boolean isEditingScriptRunning() {
return (fIgnoreOutlinePageSelection > 0);
}
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);
try {
editingScriptStarted();
setSelection(reference, !isActivePart());
} finally {
editingScriptEnded();
}
}
/*
* @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) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part != null && part.equals(this);
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fSourceViewerDecorationSupport != null) {
fSourceViewerDecorationSupport.dispose();
fSourceViewerDecorationSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
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);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, 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);
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (OVERVIEW_RULER.equals(property)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null &&
(LINE_NUMBER_COLOR.equals(property) ||
PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(1);
}
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @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(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (JavaPartitionScanner.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) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
int lineOffset;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/*
* @see AbstractTextEditor#handleCursorPositionChanged()
*/
protected void handleCursorPositionChanged() {
super.handleCursorPositionChanged();
if (!isEditingScriptRunning() && fUpdater != null)
fUpdater.post();
}
/**
* Initializes the given line number ruler column from the preference store.
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
rulerColumn.redraw();
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
fLineNumberRulerColumn= new LineNumberRulerColumn();
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
return ruler;
}
/*
* @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);
fSourceViewerDecorationSupport.install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
}
protected void showOverviewRuler() {
if (fOverviewRuler != null) {
if (getSourceViewer() instanceof ISourceViewerExtension) {
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
fSourceViewerDecorationSupport.updateOverviewDecorations();
}
}
}
protected void hideOverviewRuler() {
if (getSourceViewer() instanceof ISourceViewerExtension) {
fSourceViewerDecorationSupport.hideAnnotationOverview();
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
}
}
protected boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
protected void configureSourceViewerDecorationSupport() {
fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.UNKNOWN, UNKNOWN_INDICATION_COLOR, UNKNOWN_INDICATION, UNKNOWN_INDICATION_IN_OVERVIEW_RULER, 0);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.BOOKMARK, BOOKMARK_INDICATION_COLOR, BOOKMARK_INDICATION, BOOKMARK_INDICATION_IN_OVERVIEW_RULER, 1);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.TASK, TASK_INDICATION_COLOR, TASK_INDICATION, TASK_INDICATION_IN_OVERVIEW_RULER, 2);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.SEARCH, SEARCH_RESULT_INDICATION_COLOR, SEARCH_RESULT_INDICATION, SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, 3);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.WARNING, WARNING_INDICATION_COLOR, WARNING_INDICATION, WARNING_INDICATION_IN_OVERVIEW_RULER, 4);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.ERROR, ERROR_INDICATION_COLOR, ERROR_INDICATION, ERROR_INDICATION_IN_OVERVIEW_RULER, 5);
fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
}
/**
* 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();
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
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());
}
/**
* Ses 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);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Jumps to the error next according to the given direction.
*/
public void gotoError(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position errorPosition= new Position(0, 0);
IJavaAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition);
if (nextError != null) {
IMarker marker= null;
if (nextError instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextError).getMarker();
else {
Iterator e= nextError.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
setStatusLineErrorMessage(nextError.getMessage());
} else {
setStatusLineErrorMessage(null);
}
}
private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
IJavaAnnotation nextError= null;
Position nextErrorPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, false);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
if (a.hasOverlay() || !a.isProblem())
continue;
Position p= model.getPosition((Annotation) a);
if (!p.includes(offset)) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextError == null || currentDistance < distance) {
distance= currentDistance;
nextError= a;
nextErrorPosition= p;
}
}
}
if (nextErrorPosition != null) {
errorPosition.setOffset(nextErrorPosition.getOffset());
errorPosition.setLength(nextErrorPosition.getLength());
}
return nextError;
}
}
|
32,893 |
Bug 32893 Workspace Compatibility Problems 2.0 -> 2.1
|
Build 2.1 RC1 This PR collects problems related to opening a 2.0 workspace with 2.1.
|
resolved fixed
|
4d635cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T16:54:21Z | 2003-02-25T08:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.IPath;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
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.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.plugin.AbstractUIPlugin;
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.corext.javadoc.JavaDocLocations;
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.preferences.MembersOrderPreferenceCache;
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 {
// TODO: Evaluate if we should move these ID's to JavaUI
/**
* The id of the best match hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_BESTMATCH_HOVER= "org.eclipse.jdt.ui.BestMatchHover"; //$NON-NLS-1$
/**
* The id of the source code hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_SOURCE_HOVER= "org.eclipse.jdt.ui.JavaSourceHover"; //$NON-NLS-1$
/**
* The id of the javadoc hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_JAVADOC_HOVER= "org.eclipse.jdt.ui.JavadocHover"; //$NON-NLS-1$
/**
* The id of the problem hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_PROBLEM_HOVER= "org.eclipse.jdt.ui.ProblemHover"; //$NON-NLS-1$
private static JavaPlugin fgJavaPlugin;
private CompilationUnitDocumentProvider 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;
private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
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() {
return getActiveWorkbenchWindow().getShell();
}
/**
* 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();
}
/* package */ static IPath getInstallLocation() {
return new Path(getDefault().getDescriptor().getInstallURL().getFile());
}
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();
/*
* Backward 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.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
fFontPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
}
};
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.shutdownJavadocLocations();
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public synchronized CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public synchronized IWorkingCopyManager getWorkingCopyManager() {
return getCompilationUnitDocumentProvider();
}
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();
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));
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(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);
}
}
|
32,893 |
Bug 32893 Workspace Compatibility Problems 2.0 -> 2.1
|
Build 2.1 RC1 This PR collects problems related to opening a 2.0 workspace with 2.1.
|
resolved fixed
|
4d635cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T16:54:21Z | 2003-02-25T08:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/BestMatchHover.java
|
package org.eclipse.jdt.internal.ui.text.java.hover;
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Caution: this implementation is a layer breaker and contains some "shortcuts"
*/
public class BestMatchHover extends AbstractJavaEditorTextHover {
private static class JavaEditorTextHoverDescriptorComparator implements Comparator {
/*
* @see Comparator#compare(Object, Object)
*/
public int compare(Object object0, Object object1) {
JavaEditorTextHoverDescriptor element0= (JavaEditorTextHoverDescriptor)object0;
JavaEditorTextHoverDescriptor element1= (JavaEditorTextHoverDescriptor)object1;
String id0= element0.getId();
String id1= element1.getId();
if (id0 != null && id0.equals(id1))
return 0;
if (id0 != null && JavaProblemHover.isJavaProblemHover(id0))
return -1;
if (id1 != null && JavaProblemHover.isJavaProblemHover(id1))
return +1;
// now compare non-problem hovers
if (element0.dependsOn(element1))
return -1;
if (element1.dependsOn(element0))
return +1;
return 0;
}
}
protected String fCurrentPerspectiveId;
protected List fTextHoverSpecifications;
protected List fInstantiatedTextHovers;
public BestMatchHover() {
installTextHovers();
}
public BestMatchHover(IEditorPart editor) {
this();
setEditor(editor);
}
/**
* Installs all text hovers.
*/
private void installTextHovers() {
// initialize lists - indicates that the initialization happened
fTextHoverSpecifications= new ArrayList(2);
fInstantiatedTextHovers= new ArrayList(2);
// populate list
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
for (int i= 0; i < hoverDescs.length; i++) {
// ensure that we don't add ourselves to the list
if (!JavaPlugin.ID_BESTMATCH_HOVER.equals(hoverDescs[i].getId()))
fTextHoverSpecifications.add(hoverDescs[i]);
}
Collections.sort(fTextHoverSpecifications, new JavaEditorTextHoverDescriptorComparator());
}
private void checkTextHovers() {
if (fTextHoverSpecifications.size() == 0)
return;
for (Iterator iterator= new ArrayList(fTextHoverSpecifications).iterator(); iterator.hasNext(); ) {
JavaEditorTextHoverDescriptor spec= (JavaEditorTextHoverDescriptor) iterator.next();
IJavaEditorTextHover hover= spec.createTextHover();
if (hover != null) {
hover.setEditor(getEditor());
addTextHover(hover);
fTextHoverSpecifications.remove(spec);
}
}
}
protected void addTextHover(ITextHover hover) {
if (!fInstantiatedTextHovers.contains(hover))
fInstantiatedTextHovers.add(hover);
}
/*
* @see ITextHover#getHoverInfo(ITextViewer, IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
checkTextHovers();
if (fInstantiatedTextHovers == null)
return null;
for (Iterator iterator= fInstantiatedTextHovers.iterator(); iterator.hasNext(); ) {
ITextHover hover= (ITextHover) iterator.next();
String s= hover.getHoverInfo(textViewer, hoverRegion);
if (s != null && s.trim().length() > 0)
return s;
}
return null;
}
}
|
32,893 |
Bug 32893 Workspace Compatibility Problems 2.0 -> 2.1
|
Build 2.1 RC1 This PR collects problems related to opening a 2.0 workspace with 2.1.
|
resolved fixed
|
4d635cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T16:54:21Z | 2003-02-25T08:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaProblemHover.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.text.java.hover;
import java.util.Iterator;
import org.eclipse.jface.text.IRegion;
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.IAnnotationModel;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator;
import org.eclipse.jdt.internal.ui.text.HTMLPrinter;
public class JavaProblemHover extends AbstractJavaEditorTextHover {
/*
* Formats a message as HTML text.
*/
private String formatMessage(String message) {
StringBuffer buffer= new StringBuffer();
HTMLPrinter.addPageProlog(buffer);
HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message));
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
/*
* @see ITextHover#getHoverInfo(ITextViewer, IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
if (getEditor() == null)
return null;
IDocumentProvider provider= JavaPlugin.getDefault().getCompilationUnitDocumentProvider();
IAnnotationModel model= provider.getAnnotationModel(getEditor().getEditorInput());
if (model != null) {
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
Position p= model.getPosition(a);
if (p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
String msg= ((IJavaAnnotation) a).getMessage();
if (msg != null && msg.trim().length() > 0)
return formatMessage(msg);
}
}
}
return null;
}
/*
* @see IJavaEditorTextHover#setEditor(IEditorPart)
*/
public void setEditor(IEditorPart editor) {
if (editor instanceof CompilationUnitEditor)
super.setEditor(editor);
else
super.setEditor(null);
}
static boolean isJavaProblemHover(String id) {
return JavaPlugin.ID_PROBLEM_HOVER.equals(id);
}
}
|
32,893 |
Bug 32893 Workspace Compatibility Problems 2.0 -> 2.1
|
Build 2.1 RC1 This PR collects problems related to opening a 2.0 workspace with 2.1.
|
resolved fixed
|
4d635cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T16:54:21Z | 2003-02-25T08:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. 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-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.text.IJavaColorConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage;
/**
* Preference constants used in the JDT-UI preference store. Clients should only read the
* JDT-UI preference store using these values. Clients are not allowed to modify the
* preference store programmatically.
*
* @since 2.0
*/
public class PreferenceConstants {
private PreferenceConstants() {
}
/**
* A named preference that controls return type rendering of methods in the UI.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> return types
* are rendered
* </p>
*/
public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.jdt.ui.methodreturntype";//$NON-NLS-1$
/**
* A named preference that controls if override indicators are rendered in the UI.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> override
* indicators are rendered
* </p>
*/
public static final String APPEARANCE_OVERRIDE_INDICATOR= "org.eclipse.jdt.ui.overrideindicator";//$NON-NLS-1$
/**
* A named preference that defines the pattern used for package name compression.
* <p>
* Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern
* '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'.
* </p>
*/
public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$
/**
* A named preference that controls if package name compression is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW
*/
public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$
/**
* A named preference that controls if empty inner packages are folded in
* the hierarchical mode of the package explorer.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> empty
* inner packages are folded.
* </p>
* @since 2.1
*/
public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$
/**
* A named preference that defines how member elements are ordered by the
* Java views using the <code>JavaElementSorter</code>.
* <p>
* Value is of type <code>String</code>: A comma separated list of the
* following entries. Each entry must be in the list, no duplication. List
* order defines the sort order.
* <ul>
* <li><b>T</b>: Types</li>
* <li><b>C</b>: Constructors</li>
* <li><b>I</b>: Initializers</li>
* <li><b>M</b>: Methods</li>
* <li><b>F</b>: Fields</li>
* <li><b>SI</b>: Static Initializers</li>
* <li><b>SM</b>: Static Methods</li>
* <li><b>SF</b>: Static Fields</li>
* </ul>
* </p>
* @since 2.1
*/
public static final String APPEARANCE_MEMBER_SORT_ORDER= "outlinesortoption"; //$NON-NLS-1$
/**
* A named preference that controls if prefix removal during setter/getter generation is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated Use JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
*/
public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$
/**
* A named preference that holds a list of prefixes to be removed from a local variable to compute setter
* and gettter names.
* <p>
* Value is of type <code>String</code>: comma separated list of prefixed
* </p>
*
* @deprecated Use JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
*/
public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$
/**
* A named preference that controls if suffix removal during setter/getter generation is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated Use JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
*/
public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$
/**
* A named preference that holds a list of suffixes to be removed from a local variable to compute setter
* and getter names.
* <p>
* Value is of type <code>String</code>: comma separated list of suffixes
* </p>
* @deprecated Use setting from JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_SUFFIXES and CODEASSIST_STATIC_FIELD_SUFFIXES)
*/
public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$
/**
* A named preference that controls if comment stubs will be added
* automatically to newly created types and methods.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$
/**
* A named preference that controls if a comment stubs will be added
* automatocally to newly created types and methods.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precice).
*/
public static final String CODEGEN__JAVADOC_STUBS= CODEGEN_ADD_COMMENTS;
/**
* A named preference that controls if a non-javadoc comment gets added to methods generated via the
* "Override Methods" operation.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated New code template story: user can
* specify the overriding method comment.
*/
public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$
/**
* A named preference that controls if a file comment gets added to newly created files.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated New code template story: user can
* specify the new type code template.
*/
public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$
/**
* A named preference that holds a list of comma separated package names. The list specifies the import order used by
* the "Organize Imports" opeation.
* <p>
* Value is of type <code>String</code>: semicolon separated list of package
* names
* </p>
*/
public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.jdt.ui.importorder"; //$NON-NLS-1$
/**
* A named preference that specifies the number of imports added before a star-import declaration is used.
* <p>
* Value is of type <code>Int</code>: positive value specifing the number of non star-import is used
* </p>
*/
public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.jdt.ui.ondemandthreshold"; //$NON-NLS-1$
/**
* A named preferences that controls if types that start with a lower case letters get added by the
* "Organize Import" operation.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.jdt.ui.ignorelowercasenames"; //$NON-NLS-1$
/**
* A named preference that speficies whether children of a compilation unit are shown in the package explorer.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String SHOW_CU_CHILDREN= "org.eclipse.jdt.ui.packages.cuchildren"; //$NON-NLS-1$
/**
* A named preference that controls whether the package explorer's selection is linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String LINK_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the hierarchy view's selection is linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String LINK_TYPEHIERARCHY_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the projects view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_PROJECTS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.projectstoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the packages view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.packagestoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the types view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_TYPES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.typestoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the members view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_MEMBERS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.memberstoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether new projects are generated using source and output folder.
* <p>
* Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and
* output folder. If <code>false</code> source and output folder equals to the project.
* </p>
*/
public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$
/**
* A named preference that specifies the source folder name used when creating a new Java project. Value is inactive
* if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @see #SRCBIN_FOLDERS_IN_NEWPROJ
*/
public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$
/**
* A named preference that specifies the output folder name used when creating a new Java project. Value is inactive
* if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @see #SRCBIN_FOLDERS_IN_NEWPROJ
*/
public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$
/**
* A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library
* consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the
* JRE on the new project's classpath.
* <p>
* Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries.
* <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients
* should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string
* and the methods <code>decodeJRELibraryDescription(String)</code> and <code>
* decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array
* of classpath entries from an encoded string.
* </p>
*
* @see #NEWPROJECT_JRELIBRARY_INDEX
* @see #encodeJRELibrary(String, IClasspathEntry[])
* @see #decodeJRELibraryDescription(String)
* @see #decodeJRELibraryClasspathEntries(String)
*/
public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$
/**
* A named preferences that specifies the current active JRE library.
* <p>
* Value is of type <code>Int</code>: an index into the list of possible JRE libraries.
* </p>
*
* @see #NEWPROJECT_JRELIBRARY_LIST
*/
public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$
/**
* A named preference that controls if a new type hierarchy gets opened in a
* new type hierarchy perspective or inside the type hierarchy view part.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code>
* OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>.
* </p>
*
* @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE
* @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART
*/
public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>.
*
* @see #OPEN_TYPE_HIERARCHY
*/
public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>.
*
* @see #OPEN_TYPE_HIERARCHY
*/
public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$
/**
* A named preference that controls the behaviour when double clicking on a container in the packages view.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* DOUBLE_CLICK_GOES_INTO</code> or <code>
* DOUBLE_CLICK_EXPANDS</code>.
* </p>
*
* @see #DOUBLE_CLICK_EXPANDS
* @see #DOUBLE_CLICK_GOES_INTO
*/
public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>DOUBLE_CLICK</code>.
*
* @see #DOUBLE_CLICK
*/
public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>DOUBLE_CLICK</code>.
*
* @see #DOUBLE_CLICK
*/
public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$
/**
* A named preference that controls whether Java views update their presentation while editing or when saving the
* content of an editor.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* UPDATE_ON_SAVE</code> or <code>
* UPDATE_WHILE_EDITING</code>.
* </p>
*
* @see #UPDATE_ON_SAVE
* @see #UPDATE_WHILE_EDITING
*/
public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
*
* @see #UPDATE_JAVA_VIEWS
*/
public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
*
* @see #UPDATE_JAVA_VIEWS
*/
public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$
/**
* A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard.
* <p>
* Value is of type <code>String</code>.
* </p>
*/
public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when no control key is
* pressed.
*
* @see JavaUI
* @since 2.1
*/
public static final String EDITOR_TEXT_HOVER_MODIFIERS= "hoverModifiers"; //$NON-NLS-1$
/**
* A named preference that controls whether bracket matching highlighting is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$
/**
* A named preference that holds the color used to highlight matching brackets.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the current line highlighting is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$
/**
* A named preference that holds the color used to highlight the current line.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the print margin is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render the print margin.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$
/**
* Print margin column. Int value.
*/
public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$
/**
* A named preference that holds the color used for the find/replace scope.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE;
/**
* A named preference that specifies if the editor uses spaces for tabs.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used
* in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab
* key.
* </p>
*/
public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$
/**
* A named preference that holds the number of spaces used per tab in the editor.
* <p>
* Value is of type <code>Int</code>: positive int value specifying the number of
* spaces per tab.
* </p>
*/
public final static String EDITOR_TAB_WIDTH= "org.eclipse.jdt.ui.editor.tab.width"; //$NON-NLS-1$
/**
* A named preference that controls whether the outline view selection
* should stay in sync with with the element at the current cursor position.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$
/**
* A named preference that controls if correction indicators are shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows problem indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render problem indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_PROBLEM_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$
/**PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
* A named preference that controls whether the editor shows warning indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render warning indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_WARNING_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows task indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render task indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_TASK_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows bookmark
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render bookmark indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_BOOKMARK_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows search
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render search indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_SEARCH_RESULT_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows unknown
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render unknown
* indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_UNKNOWN_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows error
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows warning
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows task
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* bookmark indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* search result indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* unknown indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close strings' feature
* is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'wrap strings' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close brackets' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close braces' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close java docs' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'add JavaDoc tags' feature
* is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'format Javadoc tags'
* feature is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_FORMAT_JAVADOCS= "autoFormatJavaDocs"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'smart paste' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'smart home-end' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END;
/**
* A named preference that controls if temporary problems are evaluated and shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$
/**
* A named preference that controls if the overview ruler is shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls if the line number ruler is shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render line numbers inside the line number ruler.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @see #EDITOR_LINE_NUMBER_RULER
*/
public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render linked positions inside code templates.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$
/**
* A named preference that holds the color used as the text foreground.
* This value has not effect if the system default color is used.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND;
/**
* A named preference that describes if the system default foreground color
* is used as the text foreground.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT;
/**
* A named preference that holds the color used as the text background.
* This value has not effect if the system default color is used.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND;
/**
* A named preference that describes if the system default background color
* is used as the text background.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT;
/**
* Preference key suffix for bold text style preference keys.
*/
public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render multi line comments.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT;
/**
* The symbolic font name for the Java editor text font
* (value <code>"org.eclipse.jdt.ui.editors.textfont"</code>).
*
* @since 2.1
*/
public final static String EDITOR_TEXT_FONT= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$
/**
* A named preference that controls whether multi line comments are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered
* in bold. If <code>false</code> the are rendered using no font style attribute.
* </p>
*/
public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render single line comments.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT;
/**
* A named preference that controls whether sinle line comments are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered
* in bold. If <code>false</code> the are rendered using no font style attribute.
* </p>
*/
public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render java keywords.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD;
/**
* A named preference that controls whether keywords are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render string constants.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING;
/**
* A named preference that controls whether string constants are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render java default text.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT;
/**
* A named preference that controls whether Java default text is rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render task tags.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_TASK_TAG_COLOR= IJavaColorConstants.TASK_TAG;
/**
* A named preference that controls whether task tags are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_TASK_TAG_BOLD= IJavaColorConstants.TASK_TAG + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc keywords.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD;
/**
* A named preference that controls whether javadoc keywords are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc tags.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG;
/**
* A named preference that controls whether javadoc tags are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc links.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK;
/**
* A named preference that controls whether javadoc links are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc default text.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT;
/**
* A named preference that controls whether javadoc default text is rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used for 'linked-mode' underline.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$
/**
* A named preference that controls whether hover tooltips in the editor are turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when no control key is
* pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover
* contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS}
*/
public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS}
*/
public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>SHIFT</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS}
*/
public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + ALT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + ALT + SHIFT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + SHIFT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
* @deprecated Will be removed in one of the next builds.
*/
public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>ALT</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code>,
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS}
* @since 2.1
*/
public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$
/**
* A string value used by the named preferences for hover configuration to
* descibe that no hover should be shown for the given key modifiers.
* @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS}
* @since 2.1
*/
public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$
/**
* A string value used by the named preferences for hover configuration to
* descibe that the default hover should be shown for the given key
* modifiers. The default hover is described by the
* <code>EDITOR_DEFAULT_HOVER</code> property.
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS}
*/
public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$
/**
* A named preference that defines the hover named the 'default hover'.
* Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover
* contributed as <code>javaEditorTextHovers</code>.
* </p>
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS}
*/
public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$
/**
* A named preference that controls if segmented view (show selected element only) is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$
/**
* A named preference that controls if browser like links are turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String EDITOR_BROWSER_LIKE_LINKS= "browserLikeLinks"; //$NON-NLS-1$
/**
* A named preference that controls the key modifier for browser like links.
* <p>
* Value is of type <code>String</code>.
* </p>
*/
public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER= "browserLikeLinksKeyModifier"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist gets auto activated.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$
/**
* A name preference that holds the auto activation delay time in milli seconds.
* <p>
* Value is of type <code>Int</code>.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$
/**
* A named preference that controls if code assist contains only visible proposals.
* <p>
* Value is of type <code>Boolean</code>. if <code>true<code> code assist only contains visible members. If
* <code>false</code> all members are included.
* </p>
*/
public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist inserts a
* proposal automatically if only one proposal is available.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist adds import
* statements.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist only inserts
* completions. If set to false the proposals can also _replace_ code.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$
/**
* A named preference that controls whether code assist proposals filtering is case sensitive or not.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$
/**
* A named preference that defines if code assist proposals are sorted in alphabetical order.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical
* order. If <code>false</code> that are unsorted.
* </p>
*/
public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$
/**
* A named preference that controls if argument names are filled in when a method is selected from as list
* of code assist proposal.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$
/**
* A named preference that controls if method arguments are guessed when a
* method is selected from as list of code assist proposal.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$
/**
* A named preference that holds the characters that auto activate code assist in Java code.
* <p>
* Value is of type <code>Sring</code>. All characters that trigger auto code assist in Java code.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$
/**
* A named preference that holds the characters that auto activate code assist in Javadoc.
* <p>
* Value is of type <code>Sring</code>. All characters that trigger auto code assist in Javadoc.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$
/**
* A named preference that holds the background color used in the code assist selection dialog.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code assist selection dialog.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$
/**
* A named preference that holds the background color used for parameter hints.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code assist selection dialog
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$
/**
* A named preference that holds the background color used in the code
* assist selection dialog to mark replaced code.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code
* assist selection dialog to mark replaced code.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$
/**
* A named preference that controls the behaviour of the refactoring wizard for showing the error page.
* <p>
* Value is of type <code>String</code>. Valid values are:
* <code>REFACTOR_FATAL_SEVERITY</code>,
* <code>REFACTOR_ERROR_SEVERITY</code>,
* <code>REFACTOR_WARNING_SEVERITY</code>
* <code>REFACTOR_INFO_SEVERITY</code>,
* <code>REFACTOR_OK_SEVERITY</code>.
* </p>
*
* @see #REFACTOR_FATAL_SEVERITY
* @see #REFACTOR_ERROR_SEVERITY
* @see #REFACTOR_WARNING_SEVERITY
* @see #REFACTOR_INFO_SEVERITY
* @see #REFACTOR_OK_SEVERITY
*/
public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$
/**
* A named preference thet controls whether all dirty editors are automatically saved before a refactoring is
* executed.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$
/**
* A named preference that controls if the Java Browsing views are linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @see #LINK_PACKAGES_TO_EDITOR
*/
public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$
/**
* A named preference that controls the layout of the Java Browsing views vertically. Boolean value.
* <p>
* Value is of type <code>Boolean</code>. If <code>true<code> the views are stacked vertical.
* If <code>false</code> they are stacked horizontal.
* </p>
*/
public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.jdt.ui.browsing.stackVertically"; //$NON-NLS-1$
/**
* A named preference that controls if templates are formatted when applied.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 2.1
*/
public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.jdt.ui.template.format"; //$NON-NLS-1$
public static void initializeDefaultValues(IPreferenceStore store) {
store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false);
// JavaBasePreferencePage
store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, false);
store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false);
store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART);
store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS);
store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING);
store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true);
store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true);
store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true);
store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true);
// AppearancePreferencePage
store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false);
store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false);
store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true);
store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true);
store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false);
store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$
store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true);
// ImportOrganizePreferencePage
store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$
store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99);
store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true);
// ClasspathVariablesPreferencePage
// CodeFormatterPreferencePage
// CompilerPreferencePage
// no initialization needed
// RefactoringPreferencePage
store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY);
store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false);
// TemplatePreferencePage
store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true);
// CodeGenerationPreferencePage
// compatibility code
if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) {
String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX);
if (prefix.length() > 0) {
JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, prefix);
store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX);
store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX);
}
}
if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) {
String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX);
if (suffix.length() > 0) {
JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffix);
store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX);
store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX);
}
}
store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true);
// MembersOrderPreferencePage
store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SI,SF,SM,I,F,C,M"); //$NON-NLS-1$
// must add here to guarantee that it is the first in the listener list
store.addPropertyChangeListener(JavaPlugin.getDefault().getMemberOrderPreferenceCache());
// JavaEditorPreferencePage
store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192,192));
store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224));
store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false);
store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180));
store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0 , 128));
store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, true);
store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, 200 , 45));
store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, true);
store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, 255));
store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, 164, 99));
store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new RGB(192, 192, 192));
store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, 0));
store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true);
store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, false);
store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true);
store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true);
store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200 , 100));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255));
store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true);
store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true);
store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4);
store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95));
store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95));
store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85));
store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255));
store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0));
store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191));
store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false);
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true);
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500);
store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true);
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0));
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$
store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true);
store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false);
store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false);
store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true);
store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true);
store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false);
store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true);
store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true);
store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true);
store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true);
store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false);
String ctrl= Action.findModifierString(SWT.CTRL);
store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$
store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true);
store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, "Ctrl"); //$NON-NLS-1$
// do more complicated stuff
NewJavaProjectPreferencePage.initDefaults(store);
}
/**
* Returns the JDT-UI preference store.
*
* @return the JDT-UI preference store
*/
public static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/**
* Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>.
*
* @param description a string value describing the JRE library. The description is used
* to indentify the JDR library in the UI
* @param entries an array of classpath entries to be encoded
*
* @return the encoded string.
*/
public static String encodeJRELibrary(String description, IClasspathEntry[] entries) {
return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries);
}
/**
* Decodes an encoded JRE library and returns its description string.
*
* @return the description of an encoded JRE library
*
* @see #encodeJRELibrary(String, IClasspathEntry[])
*/
public static String decodeJRELibraryDescription(String encodedLibrary) {
return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary);
}
/**
* Decodes an encoded JRE library and returns its classpath entries.
*
* @return the array of classpath entries of an encoded JRE library.
*
* @see #encodeJRELibrary(String, IClasspathEntry[])
*/
public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) {
return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary);
}
/**
* Returns the current configuration for the JRE to be used as default in new Java projects.
* This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST
* </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>.
*
* @return the current default set of classpath entries
*
* @see #NEWPROJECT_JRELIBRARY_LIST
* @see #NEWPROJECT_JRELIBRARY_INDEX
*/
public static IClasspathEntry[] getDefaultJRELibrary() {
return NewJavaProjectPreferencePage.getDefaultJRELibrary();
}
}
|
33,034 |
Bug 33034 Deleting methods from inner classes does not update members view
|
If you have an inner class shown expanded in the outline, and then delete a method from it, the outline does not update the new view. It is only when the outline view is closed and reopened that the correct methods are shown. Eclipse 2.1RC1 on Windows 2000 and Mac OS X.2.4
|
verified fixed
|
052f9a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T17:26:13Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2003.
* All Rights Reserved.
*/
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.IMember;
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.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
class JavaBrowsingContentProvider extends StandardJavaElementContentProvider implements IElementChangedListener {
private StructuredViewer fViewer;
private Object fInput;
private JavaBrowsingPart fBrowsingPart;
public JavaBrowsingContentProvider(boolean provideMembers, JavaBrowsingPart browsingPart) {
super(provideMembers, reconcileJavaViews());
fBrowsingPart= browsingPart;
fViewer= fBrowsingPart.getViewer();
JavaCore.addElementChangedListener(this);
}
private static boolean reconcileJavaViews() {
return PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
}
public Object[] getChildren(Object element) {
if (!exists(element))
return NO_CHILDREN;
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;
}
}
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
ISourceReference[] sourceRefs;
if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
sourceRefs= fragment.getCompilationUnits();
if (getProvideWorkingCopy()) {
for (int i= 0; i < sourceRefs.length; i++) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)sourceRefs[i]);
if (wc != null)
sourceRefs[i]= (ICompilationUnit)wc;
}
}
}
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 (getProvideWorkingCopy()) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)parent);
if (wc != null) {
parent= (IParent)wc;
IMember wcType= EditorUtility.getWorkingCopy(type);
if (wcType != null)
type= (IType)wcType;
}
}
}
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= (IPackageFragmentRoot)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(((IWorkingCopy)element).getOriginal((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 (kind == IJavaElementDelta.CHANGED && fBrowsingPart.isValidElement(element)) {
if ((flags & IJavaElementDelta.F_CHILDREN) == 0 && (flags & IJavaElementDelta.F_MODIFIERS) == 0)
postRefresh(element);
if ((flags & IJavaElementDelta.F_FINE_GRAINED) == 0 && (flags & IJavaElementDelta.F_MODIFIERS) != 0)
postUpdateIcon(element);
}
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) {
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((IJavaElement)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((IJavaElement)element);
ctrl.setRedraw(true);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fBrowsingPart.setProcessSelectionEvents(false);
try {
Display currentDisplay= Display.getCurrent();
if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()))
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;
}
}
|
32,531 |
Bug 32531 NPE importing preferences
|
Build id: 200302211557 Got error messages when importing preferences. I couldn't reproduce the problem anymore. Will attach stack traces (two generated in a row). Top entries are: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.rootsAndC ontainers(PackageExplorerContentProvider.java:153) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.getChildr en(PackageExplorerContentProvider.java:131) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4.getFilteredChildre n(PackageExplorerPart.java:352) at org.eclipse.jface.viewers.StructuredViewer.getSortedChildren (StructuredViewer.java:555) at org.eclipse.jface.viewers.AbstractTreeViewer.updateChildren (AbstractTreeViewer.java:1282) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:925) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:934) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:895) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:881) at org.eclipse.jface.viewers.StructuredViewer$7.run(StructuredViewer.java:858) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:798) at org.eclipse.jface.viewers.StructuredViewer.refresh(StructuredViewer.java:856) at org.eclipse.jface.viewers.StructuredViewer.refresh(StructuredViewer.java:818) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart.propertyChange (PackageExplorerPart.java:1062)
|
resolved fixed
|
b6f3d18
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T17:37:30Z | 2003-02-21T23:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
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.ui.JavaPlugin;
/**
* Content provider for the PackageExplorer.
*
* <p>
* Since 2.1 this content provider can provide the children for flat or hierarchical
* layout. The hierarchical layout is done by delegating to the <code>PackageFragmentProvider</code>.
* </p>
*
* @see org.eclipse.jdt.ui.StandardJavaElementContentProvider
* @see org.eclipse.jdt.internal.ui.packageview.PackageFragmentProvider
*/
class PackageExplorerContentProvider extends StandardJavaElementContentProvider implements ITreeContentProvider, IElementChangedListener {
protected TreeViewer fViewer;
protected Object fInput;
private boolean fIsFlatLayout;
private PackageFragmentProvider fPackageFragmentProvider= new PackageFragmentProvider();
private int fPendingChanges;
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider() {
}
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider(boolean provideMembers, boolean provideWorkingCopy) {
super(provideMembers, provideWorkingCopy);
}
/* (non-Javadoc)
* Method declared on IElementChangedListener.
*/
public void elementChanged(final ElementChangedEvent event) {
try {
processDelta(event.getDelta());
} catch(JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
super.dispose();
JavaCore.removeElementChangedListener(this);
fPackageFragmentProvider.dispose();
}
// ------ Code which delegates to PackageFragmentProvider ------
private boolean needsToDelegate(Object element) {
int type= -1;
if (element instanceof IJavaElement)
type= ((IJavaElement)element).getElementType();
return (!fIsFlatLayout && (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.JAVA_PROJECT));
}
public Object[] getChildren(Object parentElement) {
Object[] children= NO_CHILDREN;
try {
if (parentElement instanceof IJavaModel)
return concatenate(getJavaProjects((IJavaModel)parentElement), getNonJavaProjects((IJavaModel)parentElement));
if (parentElement instanceof ClassPathContainer)
return getContainerPackageFragmentRoots((ClassPathContainer)parentElement);
if (parentElement instanceof IProject)
return ((IProject)parentElement).members();
if (needsToDelegate(parentElement)) {
Object[] packageFragments= fPackageFragmentProvider.getChildren(parentElement);
children= getWithParentsResources(packageFragments, parentElement);
} else {
children= super.getChildren(parentElement);
}
if (parentElement instanceof IJavaProject) {
IJavaProject project= (IJavaProject)parentElement;
return rootsAndContainers(project, children);
}
else
return children;
} catch (CoreException e) {
return NO_CHILDREN;
}
}
private Object[] rootsAndContainers(IJavaProject project, Object[] roots) { //throws JavaModelException {
List result= new ArrayList(roots.length);
Set containers= new HashSet(roots.length);
for (int i= 0; i < roots.length; i++) {
if (roots[i] instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot)roots[i];
IClasspathEntry entry= null;
try {
entry= root.getRawClasspathEntry();
} catch (JavaModelException e) {
continue;
}
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER)
containers.add(entry);
else
result.add(root);
} else {
result.add(roots[i]);
}
}
for (Iterator each= containers.iterator(); each.hasNext();) {
IClasspathEntry element= (IClasspathEntry) each.next();
result.add(new ClassPathContainer(project, element));
}
return result.toArray();
}
private Object[] getContainerPackageFragmentRoots(ClassPathContainer container) throws JavaModelException {
return container.getPackageFragmentRoots();
}
private Object[] getNonJavaProjects(IJavaModel model) throws JavaModelException {
return model.getNonJavaResources();
}
public Object getParent(Object child) {
if (needsToDelegate(child)) {
return fPackageFragmentProvider.getParent(child);
} else
return super.getParent(child);
}
/**
* Returns the given objects with the resources of the parent.
*/
private Object[] getWithParentsResources(Object[] existingObject, Object parent) {
Object[] objects= super.getChildren(parent);
List list= new ArrayList();
// Add everything that is not a PackageFragment
for (int i= 0; i < objects.length; i++) {
Object object= objects[i];
if (!(object instanceof IPackageFragment)) {
list.add(object);
}
}
if (existingObject != null)
list.addAll(Arrays.asList(existingObject));
return list.toArray();
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
fPackageFragmentProvider.inputChanged(viewer, oldInput, newInput);
fViewer= (TreeViewer)viewer;
if (oldInput == null && newInput != null) {
JavaCore.addElementChangedListener(this);
} else if (oldInput != null && newInput == null) {
JavaCore.removeElementChangedListener(this);
}
fInput= newInput;
}
// ------ delta processing ------
/**
* 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.
*/
public void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
if(element.getElementType()!= IJavaElement.JAVA_MODEL && element.getElementType()!= IJavaElement.JAVA_PROJECT){
IJavaProject proj= element.getJavaProject();
if (proj == null || !proj.getProject().isOpen())
return;
}
if (!fIsFlatLayout && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
fPackageFragmentProvider.processDelta(delta);
if (processResourceDeltas(delta.getResourceDeltas(), element))
return;
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
processAffectedChildren(affectedChildren);
return;
}
if (!getProvideWorkingCopy() && isWorkingCopy(element))
return;
if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT && !isOnClassPath((ICompilationUnit)element))
return;
// handle open and closing of a project
if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) {
postRefresh(element);
return;
}
if (kind == IJavaElementDelta.REMOVED) {
// when a working copy is removed all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
Object parent= internalGetParent(element);
postRemove(element);
if (parent instanceof IPackageFragment)
postUpdateIcon((IPackageFragment)parent);
// we are filtering out empty subpackages, so we
// a package becomes empty we remove it from the viewer.
if (isPackageFragmentEmpty(element.getParent())) {
if (fViewer.testFindItem(parent) != null)
postRefresh(internalGetParent(parent));
}
return;
}
if (kind == IJavaElementDelta.ADDED) {
// when a working copy is added all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
Object parent= internalGetParent(element);
// we are filtering out empty subpackages, so we
// have to handle additions to them specially.
if (parent instanceof IPackageFragment) {
Object grandparent= internalGetParent(parent);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (parent.equals(fInput)) {
postRefresh(parent);
} else {
// refresh from grandparent if parent isn't visible yet
if (fViewer.testFindItem(parent) == null)
postRefresh(grandparent);
else {
postRefresh(parent);
}
}
return;
} else {
postAdd(parent, element);
}
}
if (element instanceof ICompilationUnit) {
if (getProvideWorkingCopy()) {
IJavaElement original= ((IWorkingCopy)element).getOriginalElement();
if (original != null)
element= original;
}
if (kind == IJavaElementDelta.CHANGED) {
postRefresh(element);
updateSelection(delta);
return;
}
}
// we don't show the contents of a compilation or IClassFile, so don't go any deeper
if ((element instanceof ICompilationUnit) || (element instanceof IClassFile))
return;
// the contents of an external JAR has changed
if (element instanceof IPackageFragmentRoot && ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0)) {
postRefresh(element);
return;
}
// the source attachment of a JAR has changed
if (element instanceof IPackageFragmentRoot && (((flags & IJavaElementDelta.F_SOURCEATTACHED) != 0 || ((flags & IJavaElementDelta.F_SOURCEDETACHED)) != 0)))
postUpdateIcon(element);
if (isClassPathChange(delta)) {
// throw the towel and do a full refresh of the affected java project.
postRefresh(element.getJavaProject());
return;
}
if (processResourceDeltas(delta.getResourceDeltas(), element))
return;
handleAffectedChildren(delta, element);
}
private void handleAffectedChildren(IJavaElementDelta delta, IJavaElement element) throws JavaModelException {
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);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (element.equals(fInput)) {
postRefresh(element);
} else {
postRefresh(parent);
}
return;
}
// more than one child changed, refresh from here downwards
if (element instanceof IPackageFragmentRoot)
postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
else
postRefresh(element);
return;
}
processAffectedChildren(affectedChildren);
}
protected void processAffectedChildren(IJavaElementDelta[] affectedChildren) throws JavaModelException {
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 selection. It finds newly added elements
* and selects them.
*/
private void updateSelection(IJavaElementDelta delta) {
final IJavaElement addedElement= findAddedElement(delta);
if (addedElement != null) {
final StructuredSelection selection= new StructuredSelection(addedElement);
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
// 19431
// if the item is already visible then select it
if (fViewer.testFindItem(addedElement) != null)
fViewer.setSelection(selection);
}
}
});
}
}
private IJavaElement findAddedElement(IJavaElementDelta delta) {
if (delta.getKind() == IJavaElementDelta.ADDED)
return delta.getElement();
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
for (int i= 0; i < affectedChildren.length; i++)
return findAddedElement(affectedChildren[i]);
return null;
}
/**
* Refreshes the Compilation unit corresponding to the workging copy
* @param iWorkingCopy
*/
private void refreshWorkingCopy(IWorkingCopy workingCopy) {
IJavaElement original= workingCopy.getOriginalElement();
if (original != null)
postRefresh(original, false);
}
private boolean isWorkingCopy(IJavaElement element) {
return (element instanceof IWorkingCopy) && ((IWorkingCopy)element).isWorkingCopy();
}
/**
* Updates the package icon
*/
private void postUpdateIcon(final IJavaElement element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
}
});
}
/**
1 * Process a resource delta.
*
* @return true if the parent got refreshed
*/
private boolean processResourceDelta(IResourceDelta delta, Object parent) {
int status= delta.getKind();
int flags= delta.getFlags();
IResource resource= delta.getResource();
// filter out changes affecting the output folder
if (resource == null)
return false;
// this could be optimized by handling all the added children in the parent
if ((status & IResourceDelta.REMOVED) != 0) {
if (parent instanceof IPackageFragment) {
// refresh one level above to deal with empty package filtering properly
postRefresh(internalGetParent(parent));
return true;
} else
postRemove(resource);
}
if ((status & IResourceDelta.ADDED) != 0) {
if (parent instanceof IPackageFragment) {
// refresh one level above to deal with empty package filtering properly
postRefresh(internalGetParent(parent));
return true;
} else
postAdd(parent, resource);
}
// open/close state change of a project
if ((flags & IResourceDelta.OPEN) != 0) {
postRefresh(internalGetParent(parent));
return true;
}
processResourceDeltas(delta.getAffectedChildren(), resource);
return false;
}
void setIsFlatLayout(boolean state) {
fIsFlatLayout= state;
}
/**
* Process resource deltas.
*
* @return true if the parent got refreshed
*/
private boolean processResourceDeltas(IResourceDelta[] deltas, Object parent) {
if (deltas == null)
return false;
if (deltas.length > 1) {
// more than one child changed, refresh from here downwards
postRefresh(parent);
return true;
}
for (int i= 0; i < deltas.length; i++) {
if (processResourceDelta(deltas[i], parent))
return true;
}
return false;
}
private void postRefresh(final Object root) {
postRefresh(root, true);
}
private void postRefresh(final Object root, final boolean updateLabels) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
fViewer.refresh(root, updateLabels);
}
}
});
}
private void postAdd(final Object parent, final Object element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
fViewer.add(parent, element);
}
}
});
}
private void postRemove(final Object element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fViewer.remove(element);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
final Runnable trackedRunnable= new Runnable() {
public void run() {
try {
r.run();
} finally {
removePendingChange();
}
}
};
if (ctrl != null && !ctrl.isDisposed()) {
addPendingChange();
try {
ctrl.getDisplay().asyncExec(trackedRunnable);
} catch (RuntimeException e) {
removePendingChange();
throw e;
} catch (Error e) {
removePendingChange();
throw e;
}
}
}
// ------ Pending change management due to the use of asyncExec in postRunnable.
public synchronized boolean hasPendingChanges() {
return fPendingChanges > 0;
}
private synchronized void addPendingChange() {
fPendingChanges++;
// System.out.print(fPendingChanges);
}
private synchronized void removePendingChange() {
fPendingChanges--;
if (fPendingChanges < 0)
fPendingChanges= 0;
// System.out.print(fPendingChanges);
}
}
|
32,460 |
Bug 32460 Restoring type hierarchy on startup taking for ever
|
Build 20030221 See below an explanation of a long startup time when opening an old workspace with one hierarchy view opened and index format changed in the meantime. No progress, actually no UI shows up for 5 minutes (it is reindexing the entire world). 2.0 workspaces are likely going to be in this exact mode. I believe the hierarchy computation should time out after 5 seconds of indexes not being available (during hierarchy restoration). "ModalContext" prio=5 tid=0x13966020 nid=0x5e8 runnable [14eaf000..14eafd8c] at org.eclipse.jdt.internal.core.index.impl.Field.<init>(Field.java:48) at org.eclipse.jdt.internal.core.index.impl.Block.<init>(Block.java:34) at org.eclipse.jdt.internal.core.index.impl.IndexBlock.<init> (IndexBlock.java:22) at org.eclipse.jdt.internal.core.index.impl.GammaCompressedIndexBlock.<init> (GammaCompressedIndexBlock.java:25) at org.eclipse.jdt.internal.core.index.impl.BlocksIndexInput.getIndexBlock (BlocksIndexInput.java:104) at org.eclipse.jdt.internal.core.index.impl.BlocksIndexInput.queryEntriesPrefixedBy (BlocksIndexInput.java:281) at org.eclipse.jdt.internal.core.search.matching.SuperTypeReferencePattern.findInde xMatches(SuperTypeReferencePattern.java:129) at org.eclipse.jdt.internal.core.search.SubTypeSearchJob.search (SubTypeSearchJob.java:90) at org.eclipse.jdt.internal.core.search.PatternSearchJob.execute (PatternSearchJob.java:93) at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob (JobManager.java:267) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.searchAllPoss ibleSubTypes(IndexBasedHierarchyBuilder.java:517) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.determinePoss ibleSubTypes(IndexBasedHierarchyBuilder.java:384) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.build (IndexBasedHierarchyBuilder.java:154) at org.eclipse.jdt.internal.core.hierarchy.TypeHierarchy.compute (TypeHierarchy.java:322) at org.eclipse.jdt.internal.core.hierarchy.TypeHierarchy.refresh (TypeHierarchy.java:1368) at org.eclipse.jdt.internal.core.CreateTypeHierarchyOperation.executeOperation (CreateTypeHierarchyOperation.java:78) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:365) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:681) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.java:553) at org.eclipse.jdt.internal.core.BinaryType.newTypeHierarchy (BinaryType.java:469) at org.eclipse.jdt.internal.core.BinaryType.newTypeHierarchy (BinaryType.java:458) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.doHierarchyRefr esh(TypeHierarchyLifeCycle.java:152) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.access$0 (TypeHierarchyLifeCycle.java:137) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle$1.run (TypeHierarchyLifeCycle.java:109) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x13936D78 nid=0x5d4 in Object.wait() [14def000..14defd8c] at java.lang.Object.wait(Native Method) - waiting on <04259690> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run (AbstractReconciler.java:161) - locked <04259690> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x1388B000 nid=0x3a4 in Object.wait() [14adf000..14adfd8c] at java.lang.Object.wait(Native Method) - waiting on <03FAC298> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run (AbstractReconciler.java:161) - locked <03FAC298> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "Java indexing" daemon prio=4 tid=0x1353E7F0 nid=0x614 waiting on condition [1429f000..1429fd8c] at java.lang.Thread.sleep(Native Method) at org.eclipse.jdt.internal.core.search.processing.JobManager.run (JobManager.java:334) at java.lang.Thread.run(Thread.java:536) "Signal Dispatcher" daemon prio=10 tid=0x00904228 nid=0x4f0 runnable [0..0] "Finalizer" daemon prio=9 tid=0x008FDCD0 nid=0x4ec in Object.wait() [133cf000..133cfd8c] at java.lang.Object.wait(Native Method) - waiting on <03950138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111) - locked <03950138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) "Reference Handler" daemon prio=10 tid=0x0023D3B0 nid=0x630 in Object.wait() [1338f000..1338fd8c] at java.lang.Object.wait(Native Method) - waiting on <039501A0> (a java.lang.ref.Reference$Lock) at java.lang.Object.wait(Object.java:426) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:113) - locked <039501A0> (a java.lang.ref.Reference$Lock) "main" prio=5 tid=0x00234CF8 nid=0x640 runnable [6e000..6fc40] at org.eclipse.swt.internal.win32.OS.WaitMessage(Native Method) at org.eclipse.swt.widgets.Display.sleep(Display.java:2064) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block (ModalContext.java:131) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:255) at org.eclipse.jface.window.ApplicationWindow$1.run (ApplicationWindow.java:431) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jface.window.ApplicationWindow.run (ApplicationWindow.java:428) at org.eclipse.ui.internal.WorkbenchWindow.run (WorkbenchWindow.java:1363) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.ensureRefreshed TypeHierarchy(TypeHierarchyLifeCycle.java:121) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.updateInput (TypeHierarchyViewPart.java:458) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.setInputElement (TypeHierarchyViewPart.java:439) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.restoreState (TypeHierarchyViewPart.java:1344) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.createPartContro l(TypeHierarchyViewPart.java:773) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:138) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.PartPane.createChildControl (PartPane.java:134) at org.eclipse.ui.internal.ViewPane.createChildControl (ViewPane.java:202) at org.eclipse.ui.internal.PartPane.createControl(PartPane.java:183) at org.eclipse.ui.internal.ViewPane.createControl(ViewPane.java:181) at org.eclipse.ui.internal.PartTabFolder.createPartTab (PartTabFolder.java:251) at org.eclipse.ui.internal.PartTabFolder.createControl (PartTabFolder.java:223) at org.eclipse.ui.internal.PartSashContainer.createControl (PartSashContainer.java:191) at org.eclipse.ui.internal.PerspectivePresentation.activate (PerspectivePresentation.java:96) at org.eclipse.ui.internal.Perspective.onActivate(Perspective.java:715) at org.eclipse.ui.internal.WorkbenchPage.onActivate (WorkbenchPage.java:1777) at org.eclipse.ui.internal.WorkbenchWindow$7.run (WorkbenchWindow.java:1474) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.WorkbenchWindow.setActivePage (WorkbenchWindow.java:1461) at org.eclipse.ui.internal.WorkbenchWindow.restoreState (WorkbenchWindow.java:1342) at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1132) at org.eclipse.ui.internal.Workbench.access$9(Workbench.java:1092) at org.eclipse.ui.internal.Workbench$10.run(Workbench.java:1010) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.Workbench.openPreviousWorkbenchState (Workbench.java:962) at org.eclipse.ui.internal.Workbench.init(Workbench.java:742) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1242) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) "VM Thread" prio=5 tid=0x008DD950 nid=0x5e0 runnable "VM Periodic Task Thread" prio=10 tid=0x009046F0 nid=0x634 waiting on condition "Suspend Checker Thread" prio=10 tid=0x008FDAB0 nid=0x300 runnable Startup complete: 192857ms
|
resolved fixed
|
f8abc0d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T20:57:56Z | 2003-02-21T09:33:20Z |
org.eclipse.jdt.ui/core
| |
32,460 |
Bug 32460 Restoring type hierarchy on startup taking for ever
|
Build 20030221 See below an explanation of a long startup time when opening an old workspace with one hierarchy view opened and index format changed in the meantime. No progress, actually no UI shows up for 5 minutes (it is reindexing the entire world). 2.0 workspaces are likely going to be in this exact mode. I believe the hierarchy computation should time out after 5 seconds of indexes not being available (during hierarchy restoration). "ModalContext" prio=5 tid=0x13966020 nid=0x5e8 runnable [14eaf000..14eafd8c] at org.eclipse.jdt.internal.core.index.impl.Field.<init>(Field.java:48) at org.eclipse.jdt.internal.core.index.impl.Block.<init>(Block.java:34) at org.eclipse.jdt.internal.core.index.impl.IndexBlock.<init> (IndexBlock.java:22) at org.eclipse.jdt.internal.core.index.impl.GammaCompressedIndexBlock.<init> (GammaCompressedIndexBlock.java:25) at org.eclipse.jdt.internal.core.index.impl.BlocksIndexInput.getIndexBlock (BlocksIndexInput.java:104) at org.eclipse.jdt.internal.core.index.impl.BlocksIndexInput.queryEntriesPrefixedBy (BlocksIndexInput.java:281) at org.eclipse.jdt.internal.core.search.matching.SuperTypeReferencePattern.findInde xMatches(SuperTypeReferencePattern.java:129) at org.eclipse.jdt.internal.core.search.SubTypeSearchJob.search (SubTypeSearchJob.java:90) at org.eclipse.jdt.internal.core.search.PatternSearchJob.execute (PatternSearchJob.java:93) at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob (JobManager.java:267) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.searchAllPoss ibleSubTypes(IndexBasedHierarchyBuilder.java:517) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.determinePoss ibleSubTypes(IndexBasedHierarchyBuilder.java:384) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.build (IndexBasedHierarchyBuilder.java:154) at org.eclipse.jdt.internal.core.hierarchy.TypeHierarchy.compute (TypeHierarchy.java:322) at org.eclipse.jdt.internal.core.hierarchy.TypeHierarchy.refresh (TypeHierarchy.java:1368) at org.eclipse.jdt.internal.core.CreateTypeHierarchyOperation.executeOperation (CreateTypeHierarchyOperation.java:78) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:365) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:681) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.java:553) at org.eclipse.jdt.internal.core.BinaryType.newTypeHierarchy (BinaryType.java:469) at org.eclipse.jdt.internal.core.BinaryType.newTypeHierarchy (BinaryType.java:458) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.doHierarchyRefr esh(TypeHierarchyLifeCycle.java:152) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.access$0 (TypeHierarchyLifeCycle.java:137) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle$1.run (TypeHierarchyLifeCycle.java:109) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x13936D78 nid=0x5d4 in Object.wait() [14def000..14defd8c] at java.lang.Object.wait(Native Method) - waiting on <04259690> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run (AbstractReconciler.java:161) - locked <04259690> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x1388B000 nid=0x3a4 in Object.wait() [14adf000..14adfd8c] at java.lang.Object.wait(Native Method) - waiting on <03FAC298> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run (AbstractReconciler.java:161) - locked <03FAC298> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "Java indexing" daemon prio=4 tid=0x1353E7F0 nid=0x614 waiting on condition [1429f000..1429fd8c] at java.lang.Thread.sleep(Native Method) at org.eclipse.jdt.internal.core.search.processing.JobManager.run (JobManager.java:334) at java.lang.Thread.run(Thread.java:536) "Signal Dispatcher" daemon prio=10 tid=0x00904228 nid=0x4f0 runnable [0..0] "Finalizer" daemon prio=9 tid=0x008FDCD0 nid=0x4ec in Object.wait() [133cf000..133cfd8c] at java.lang.Object.wait(Native Method) - waiting on <03950138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111) - locked <03950138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) "Reference Handler" daemon prio=10 tid=0x0023D3B0 nid=0x630 in Object.wait() [1338f000..1338fd8c] at java.lang.Object.wait(Native Method) - waiting on <039501A0> (a java.lang.ref.Reference$Lock) at java.lang.Object.wait(Object.java:426) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:113) - locked <039501A0> (a java.lang.ref.Reference$Lock) "main" prio=5 tid=0x00234CF8 nid=0x640 runnable [6e000..6fc40] at org.eclipse.swt.internal.win32.OS.WaitMessage(Native Method) at org.eclipse.swt.widgets.Display.sleep(Display.java:2064) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block (ModalContext.java:131) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:255) at org.eclipse.jface.window.ApplicationWindow$1.run (ApplicationWindow.java:431) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jface.window.ApplicationWindow.run (ApplicationWindow.java:428) at org.eclipse.ui.internal.WorkbenchWindow.run (WorkbenchWindow.java:1363) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.ensureRefreshed TypeHierarchy(TypeHierarchyLifeCycle.java:121) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.updateInput (TypeHierarchyViewPart.java:458) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.setInputElement (TypeHierarchyViewPart.java:439) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.restoreState (TypeHierarchyViewPart.java:1344) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.createPartContro l(TypeHierarchyViewPart.java:773) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:138) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.PartPane.createChildControl (PartPane.java:134) at org.eclipse.ui.internal.ViewPane.createChildControl (ViewPane.java:202) at org.eclipse.ui.internal.PartPane.createControl(PartPane.java:183) at org.eclipse.ui.internal.ViewPane.createControl(ViewPane.java:181) at org.eclipse.ui.internal.PartTabFolder.createPartTab (PartTabFolder.java:251) at org.eclipse.ui.internal.PartTabFolder.createControl (PartTabFolder.java:223) at org.eclipse.ui.internal.PartSashContainer.createControl (PartSashContainer.java:191) at org.eclipse.ui.internal.PerspectivePresentation.activate (PerspectivePresentation.java:96) at org.eclipse.ui.internal.Perspective.onActivate(Perspective.java:715) at org.eclipse.ui.internal.WorkbenchPage.onActivate (WorkbenchPage.java:1777) at org.eclipse.ui.internal.WorkbenchWindow$7.run (WorkbenchWindow.java:1474) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.WorkbenchWindow.setActivePage (WorkbenchWindow.java:1461) at org.eclipse.ui.internal.WorkbenchWindow.restoreState (WorkbenchWindow.java:1342) at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1132) at org.eclipse.ui.internal.Workbench.access$9(Workbench.java:1092) at org.eclipse.ui.internal.Workbench$10.run(Workbench.java:1010) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.Workbench.openPreviousWorkbenchState (Workbench.java:962) at org.eclipse.ui.internal.Workbench.init(Workbench.java:742) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1242) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) "VM Thread" prio=5 tid=0x008DD950 nid=0x5e0 runnable "VM Periodic Task Thread" prio=10 tid=0x009046F0 nid=0x634 waiting on condition "Suspend Checker Thread" prio=10 tid=0x008FDAB0 nid=0x300 runnable Startup complete: 192857ms
|
resolved fixed
|
f8abc0d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T20:57:56Z | 2003-02-21T09:33:20Z |
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
| |
32,460 |
Bug 32460 Restoring type hierarchy on startup taking for ever
|
Build 20030221 See below an explanation of a long startup time when opening an old workspace with one hierarchy view opened and index format changed in the meantime. No progress, actually no UI shows up for 5 minutes (it is reindexing the entire world). 2.0 workspaces are likely going to be in this exact mode. I believe the hierarchy computation should time out after 5 seconds of indexes not being available (during hierarchy restoration). "ModalContext" prio=5 tid=0x13966020 nid=0x5e8 runnable [14eaf000..14eafd8c] at org.eclipse.jdt.internal.core.index.impl.Field.<init>(Field.java:48) at org.eclipse.jdt.internal.core.index.impl.Block.<init>(Block.java:34) at org.eclipse.jdt.internal.core.index.impl.IndexBlock.<init> (IndexBlock.java:22) at org.eclipse.jdt.internal.core.index.impl.GammaCompressedIndexBlock.<init> (GammaCompressedIndexBlock.java:25) at org.eclipse.jdt.internal.core.index.impl.BlocksIndexInput.getIndexBlock (BlocksIndexInput.java:104) at org.eclipse.jdt.internal.core.index.impl.BlocksIndexInput.queryEntriesPrefixedBy (BlocksIndexInput.java:281) at org.eclipse.jdt.internal.core.search.matching.SuperTypeReferencePattern.findInde xMatches(SuperTypeReferencePattern.java:129) at org.eclipse.jdt.internal.core.search.SubTypeSearchJob.search (SubTypeSearchJob.java:90) at org.eclipse.jdt.internal.core.search.PatternSearchJob.execute (PatternSearchJob.java:93) at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob (JobManager.java:267) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.searchAllPoss ibleSubTypes(IndexBasedHierarchyBuilder.java:517) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.determinePoss ibleSubTypes(IndexBasedHierarchyBuilder.java:384) at org.eclipse.jdt.internal.core.hierarchy.IndexBasedHierarchyBuilder.build (IndexBasedHierarchyBuilder.java:154) at org.eclipse.jdt.internal.core.hierarchy.TypeHierarchy.compute (TypeHierarchy.java:322) at org.eclipse.jdt.internal.core.hierarchy.TypeHierarchy.refresh (TypeHierarchy.java:1368) at org.eclipse.jdt.internal.core.CreateTypeHierarchyOperation.executeOperation (CreateTypeHierarchyOperation.java:78) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:365) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:681) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.java:553) at org.eclipse.jdt.internal.core.BinaryType.newTypeHierarchy (BinaryType.java:469) at org.eclipse.jdt.internal.core.BinaryType.newTypeHierarchy (BinaryType.java:458) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.doHierarchyRefr esh(TypeHierarchyLifeCycle.java:152) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.access$0 (TypeHierarchyLifeCycle.java:137) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle$1.run (TypeHierarchyLifeCycle.java:109) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x13936D78 nid=0x5d4 in Object.wait() [14def000..14defd8c] at java.lang.Object.wait(Native Method) - waiting on <04259690> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run (AbstractReconciler.java:161) - locked <04259690> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x1388B000 nid=0x3a4 in Object.wait() [14adf000..14adfd8c] at java.lang.Object.wait(Native Method) - waiting on <03FAC298> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run (AbstractReconciler.java:161) - locked <03FAC298> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "Java indexing" daemon prio=4 tid=0x1353E7F0 nid=0x614 waiting on condition [1429f000..1429fd8c] at java.lang.Thread.sleep(Native Method) at org.eclipse.jdt.internal.core.search.processing.JobManager.run (JobManager.java:334) at java.lang.Thread.run(Thread.java:536) "Signal Dispatcher" daemon prio=10 tid=0x00904228 nid=0x4f0 runnable [0..0] "Finalizer" daemon prio=9 tid=0x008FDCD0 nid=0x4ec in Object.wait() [133cf000..133cfd8c] at java.lang.Object.wait(Native Method) - waiting on <03950138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111) - locked <03950138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) "Reference Handler" daemon prio=10 tid=0x0023D3B0 nid=0x630 in Object.wait() [1338f000..1338fd8c] at java.lang.Object.wait(Native Method) - waiting on <039501A0> (a java.lang.ref.Reference$Lock) at java.lang.Object.wait(Object.java:426) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:113) - locked <039501A0> (a java.lang.ref.Reference$Lock) "main" prio=5 tid=0x00234CF8 nid=0x640 runnable [6e000..6fc40] at org.eclipse.swt.internal.win32.OS.WaitMessage(Native Method) at org.eclipse.swt.widgets.Display.sleep(Display.java:2064) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block (ModalContext.java:131) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:255) at org.eclipse.jface.window.ApplicationWindow$1.run (ApplicationWindow.java:431) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jface.window.ApplicationWindow.run (ApplicationWindow.java:428) at org.eclipse.ui.internal.WorkbenchWindow.run (WorkbenchWindow.java:1363) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyLifeCycle.ensureRefreshed TypeHierarchy(TypeHierarchyLifeCycle.java:121) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.updateInput (TypeHierarchyViewPart.java:458) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.setInputElement (TypeHierarchyViewPart.java:439) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.restoreState (TypeHierarchyViewPart.java:1344) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.createPartContro l(TypeHierarchyViewPart.java:773) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:138) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.PartPane.createChildControl (PartPane.java:134) at org.eclipse.ui.internal.ViewPane.createChildControl (ViewPane.java:202) at org.eclipse.ui.internal.PartPane.createControl(PartPane.java:183) at org.eclipse.ui.internal.ViewPane.createControl(ViewPane.java:181) at org.eclipse.ui.internal.PartTabFolder.createPartTab (PartTabFolder.java:251) at org.eclipse.ui.internal.PartTabFolder.createControl (PartTabFolder.java:223) at org.eclipse.ui.internal.PartSashContainer.createControl (PartSashContainer.java:191) at org.eclipse.ui.internal.PerspectivePresentation.activate (PerspectivePresentation.java:96) at org.eclipse.ui.internal.Perspective.onActivate(Perspective.java:715) at org.eclipse.ui.internal.WorkbenchPage.onActivate (WorkbenchPage.java:1777) at org.eclipse.ui.internal.WorkbenchWindow$7.run (WorkbenchWindow.java:1474) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.WorkbenchWindow.setActivePage (WorkbenchWindow.java:1461) at org.eclipse.ui.internal.WorkbenchWindow.restoreState (WorkbenchWindow.java:1342) at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1132) at org.eclipse.ui.internal.Workbench.access$9(Workbench.java:1092) at org.eclipse.ui.internal.Workbench$10.run(Workbench.java:1010) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.Workbench.openPreviousWorkbenchState (Workbench.java:962) at org.eclipse.ui.internal.Workbench.init(Workbench.java:742) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1242) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) "VM Thread" prio=5 tid=0x008DD950 nid=0x5e0 runnable "VM Periodic Task Thread" prio=10 tid=0x009046F0 nid=0x634 waiting on condition "Suspend Checker Thread" prio=10 tid=0x008FDAB0 nid=0x300 runnable Startup complete: 192857ms
|
resolved fixed
|
f8abc0d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T20:57:56Z | 2003-02-21T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.DragSource;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.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.PartInitException;
import org.eclipse.ui.actions.ActionContext;
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.JavaModelUtil;
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.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
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.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;
/**
* 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 fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
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;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fHierarchyLifeCycle.setReconciled(isReconciled);
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) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* 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) {
if (member.getElementType() != IJavaElement.TYPE) {
// methods are working copies
if (fHierarchyLifeCycle.isReconciled()) {
member= JavaModelUtil.toWorkingCopy(member);
}
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();
}
// types are originals
member= JavaModelUtil.toOriginal(member);
if (!member.equals(fSelectedType)) {
getCurrentViewer().setSelection(new StructuredSelection(member), 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();
}
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(element);
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();
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
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;
}
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer(true);
}
IType root= getSelectableType(fInputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
fPagebook.showPage(fTypeMethodsSplitter);
}
}
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();
fMethodsViewer.dispose();
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.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) {
updateHierarchyViewer(false);
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
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.addSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
}
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.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
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){
Control control= viewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// 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$
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 < fToggleOrientationActions.length; i++) {
viewMenu.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);
IJavaElement input= 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 RefactorActionGroup(this),
new GenerateActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
initDragAndDrop();
}
/**
* 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.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(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());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
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) {
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) {
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 pagae
// 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(false);
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;
}
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
}
});
}
}
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
fMethodsViewer.refresh();
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 } );
}
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) input;
if (elem instanceof IMember) {
return elem;
} else {
int kind= elem.getElementType();
if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) {
return elem;
}
}
}
return null;
}
/*
* @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());
}
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;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
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) {
doTypeHierarchyChanged(fHierarchyLifeCycle, 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);
}
}
}
}
|
32,831 |
Bug 32831 NPE buildpaths.CPVariableElement.equals()
|
Eclipse 20030221 RH 8.0, motif Install eclipse Start eclipse with a new workspace Open the 'Classpath Variables' preference page (Window>Preferences>Java>Classpath Variables' Close the preference page doing nothing (hit ok) Re-open the 'Classpath Variables' preference page. The attached log is generated.
|
verified fixed
|
9e7b794
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T21:27:44Z | 2003-02-24T20:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
public class CPListElement {
public static final String SOURCEATTACHMENT= "sourcepath"; //$NON-NLS-1$
public static final String SOURCEATTACHMENTROOT= "rootpath"; //$NON-NLS-1$
public static final String JAVADOC= "javadoc"; //$NON-NLS-1$
public static final String OUTPUT= "output"; //$NON-NLS-1$
public static final String EXCLUSION= "exclusion"; //$NON-NLS-1$
private IJavaProject fProject;
private int fEntryKind;
private IPath fPath;
private IResource fResource;
private boolean fIsExported;
private boolean fIsMissing;
private CPListElement fParentContainer;
private IClasspathEntry fCachedEntry;
private ArrayList fChildren;
public CPListElement(IJavaProject project, int entryKind, IPath path, IResource res) {
fProject= project;
fEntryKind= entryKind;
fPath= path;
fChildren= new ArrayList();
fResource= res;
fIsExported= false;
fIsMissing= false;
fCachedEntry= null;
fParentContainer= null;
switch (entryKind) {
case IClasspathEntry.CPE_SOURCE:
createAttributeElement(OUTPUT, null);
createAttributeElement(EXCLUSION, new Path[0]);
break;
case IClasspathEntry.CPE_LIBRARY:
case IClasspathEntry.CPE_VARIABLE:
createAttributeElement(SOURCEATTACHMENT, null);
createAttributeElement(JAVADOC, null);
break;
case IClasspathEntry.CPE_PROJECT:
break;
case IClasspathEntry.CPE_CONTAINER:
try {
IClasspathContainer container= JavaCore.getClasspathContainer(fPath, fProject);
if (container != null) {
IClasspathEntry[] entries= container.getClasspathEntries();
for (int i= 0; i < entries.length; i++) {
CPListElement curr= createFromExisting(entries[i], fProject);
curr.setParentContainer(this);
fChildren.add(curr);
}
}
} catch (JavaModelException e) {
}
break;
default:
}
}
public IClasspathEntry getClasspathEntry() {
if (fCachedEntry == null) {
fCachedEntry= newClasspathEntry();
}
return fCachedEntry;
}
private IClasspathEntry newClasspathEntry() {
switch (fEntryKind) {
case IClasspathEntry.CPE_SOURCE:
IPath outputLocation= (IPath) getAttribute(OUTPUT);
IPath[] exclusionPattern= (IPath[]) getAttribute(EXCLUSION);
return JavaCore.newSourceEntry(fPath, exclusionPattern, outputLocation);
case IClasspathEntry.CPE_LIBRARY:
IPath attach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newLibraryEntry(fPath, attach, null, isExported());
case IClasspathEntry.CPE_PROJECT:
return JavaCore.newProjectEntry(fPath, isExported());
case IClasspathEntry.CPE_CONTAINER:
return JavaCore.newContainerEntry(fPath, isExported());
case IClasspathEntry.CPE_VARIABLE:
IPath varAttach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newVariableEntry(fPath, varAttach, null, isExported());
default:
return null;
}
}
/**
* Gets the classpath entry path.
* @see IClasspathEntry#getPath()
*/
public IPath getPath() {
return fPath;
}
/**
* Gets the classpath entry kind.
* @see IClasspathEntry#getEntryKind()
*/
public int getEntryKind() {
return fEntryKind;
}
/**
* Entries without resource are either non existing or a variable entry
* External jars do not have a resource
*/
public IResource getResource() {
return fResource;
}
public CPListElementAttribute setAttribute(String key, Object value) {
CPListElementAttribute attribute= findAttributeElement(key);
if (attribute == null) {
return null;
}
attribute.setValue(value);
attributeChanged(key);
return attribute;
}
private CPListElementAttribute findAttributeElement(String key) {
for (int i= 0; i < fChildren.size(); i++) {
Object curr= fChildren.get(i);
if (curr instanceof CPListElementAttribute) {
CPListElementAttribute elem= (CPListElementAttribute) curr;
if (key.equals(elem.getKey())) {
return elem;
}
}
}
return null;
}
public Object getAttribute(String key) {
CPListElementAttribute attrib= findAttributeElement(key);
if (attrib != null) {
return attrib.getValue();
}
return null;
}
private void createAttributeElement(String key, Object value) {
fChildren.add(new CPListElementAttribute(this, key, value));
}
public Object[] getChildren(boolean hideOutputFolder) {
if (hideOutputFolder && fEntryKind == IClasspathEntry.CPE_SOURCE) {
return new Object[] { findAttributeElement(EXCLUSION) };
}
return fChildren.toArray();
}
private void setParentContainer(CPListElement element) {
fParentContainer= element;
}
public CPListElement getParentContainer() {
return fParentContainer;
}
private void attributeChanged(String key) {
fCachedEntry= null;
}
/*
* @see Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (other != null && other.getClass() == getClass()) {
CPListElement elem= (CPListElement)other;
return elem.fEntryKind == fEntryKind && elem.fPath.equals(fPath);
}
return false;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fPath.hashCode() + fEntryKind;
}
/**
* Returns if a entry is missing.
* @return Returns a boolean
*/
public boolean isMissing() {
return fIsMissing;
}
/**
* Sets the 'missing' state of the entry.
*/
public void setIsMissing(boolean isMissing) {
fIsMissing= isMissing;
}
/**
* Returns if a entry is exported (only applies to libraries)
* @return Returns a boolean
*/
public boolean isExported() {
return fIsExported;
}
/**
* Sets the export state of the entry.
*/
public void setExported(boolean isExported) {
if (isExported != fIsExported) {
fIsExported = isExported;
attributeChanged(null);
}
}
/**
* Gets the project.
* @return Returns a IJavaProject
*/
public IJavaProject getJavaProject() {
return fProject;
}
public static CPListElement createFromExisting(IClasspathEntry curr, IJavaProject project) {
IPath path= curr.getPath();
IWorkspaceRoot root= project.getProject().getWorkspace().getRoot();
// get the resource
IResource res= null;
boolean isMissing= false;
URL javaDocLocation= null;
switch (curr.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
res= null;
try {
isMissing= (JavaCore.getClasspathContainer(path, project) == null);
} catch (JavaModelException e) {
isMissing= true;
}
break;
case IClasspathEntry.CPE_VARIABLE:
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
res= null;
isMissing= root.findMember(resolvedPath) == null && !resolvedPath.toFile().isFile();
javaDocLocation= JavaUI.getLibraryJavadocLocation(resolvedPath);
break;
case IClasspathEntry.CPE_LIBRARY:
res= root.findMember(path);
if (res == null) {
if (!ArchiveFileFilter.isArchivePath(path)) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
res= root.getFolder(path);
}
}
isMissing= !path.toFile().isFile(); // look for external JARs
}
javaDocLocation= JavaUI.getLibraryJavadocLocation(path);
break;
case IClasspathEntry.CPE_SOURCE:
res= root.findMember(path);
if (res == null) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
res= root.getFolder(path);
}
isMissing= true;
}
break;
case IClasspathEntry.CPE_PROJECT:
res= root.findMember(path);
isMissing= (res == null);
break;
}
CPListElement elem= new CPListElement(project, curr.getEntryKind(), path, res);
elem.setExported(curr.isExported());
elem.setAttribute(SOURCEATTACHMENT, curr.getSourceAttachmentPath());
elem.setAttribute(JAVADOC, javaDocLocation);
elem.setAttribute(OUTPUT, curr.getOutputLocation());
elem.setAttribute(EXCLUSION, curr.getExclusionPatterns());
if (project.exists()) {
elem.setIsMissing(isMissing);
}
return elem;
}
}
|
32,831 |
Bug 32831 NPE buildpaths.CPVariableElement.equals()
|
Eclipse 20030221 RH 8.0, motif Install eclipse Start eclipse with a new workspace Open the 'Classpath Variables' preference page (Window>Preferences>Java>Classpath Variables' Close the preference page doing nothing (hit ok) Re-open the 'Classpath Variables' preference page. The attached log is generated.
|
verified fixed
|
9e7b794
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T21:27:44Z | 2003-02-24T20:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPVariableElement.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.util.Assert;
public class CPVariableElement {
private String fName;
private IPath fPath;
private boolean fIsReserved;
public CPVariableElement(String name, IPath path, boolean reserved) {
Assert.isNotNull(name);
Assert.isNotNull(path);
fName= name;
fPath= path;
fIsReserved= reserved;
}
/**
* Gets the path
* @return Returns a IPath
*/
public IPath getPath() {
return fPath;
}
/**
* Sets the path
* @param path The path to set
*/
public void setPath(IPath path) {
fPath= path;
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return fName;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
fName= name;
}
/*
* @see Object#equals()
*/
public boolean equals(Object other) {
if (other.getClass().equals(getClass())) {
CPVariableElement elem= (CPVariableElement)other;
return fName.equals(elem.fName);
}
return false;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fName.hashCode();
}
/**
* Returns true if variable is reserved
* @return Returns a boolean
*/
public boolean isReserved() {
return fIsReserved;
}
/**
* Sets the isReserved
* @param isReserved The state to set
*/
public void setReserved(boolean isReserved) {
fIsReserved= isReserved;
}
}
|
32,831 |
Bug 32831 NPE buildpaths.CPVariableElement.equals()
|
Eclipse 20030221 RH 8.0, motif Install eclipse Start eclipse with a new workspace Open the 'Classpath Variables' preference page (Window>Preferences>Java>Classpath Variables' Close the preference page doing nothing (hit ok) Re-open the 'Classpath Variables' preference page. The attached log is generated.
|
verified fixed
|
9e7b794
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T21:27:44Z | 2003-02-24T20:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementImageDescriptor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.resource.CompositeImageDescriptor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
* A JavaImageDescriptor consists of a base image and several adornments. The adornments
* are computed according to the flags either passed during creation or set via the method
* <code>setAdornments</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class JavaElementImageDescriptor extends CompositeImageDescriptor {
/** Flag to render the abstract adornment */
public final static int ABSTRACT= 0x001;
/** Flag to render the final adornment */
public final static int FINAL= 0x002;
/** Flag to render the synchronized adornment */
public final static int SYNCHRONIZED= 0x004;
/** Flag to render the static adornment */
public final static int STATIC= 0x008;
/** Flag to render the runnable adornment */
public final static int RUNNABLE= 0x010;
/** Flag to render the waring adornment */
public final static int WARNING= 0x020;
/** Flag to render the error adornment */
public final static int ERROR= 0x040;
/** Flag to render the 'override' adornment */
public final static int OVERRIDES= 0x080;
/** Flag to render the 'implements' adornment */
public final static int IMPLEMENTS= 0x100;
/** Flag to render the 'constructor' adornment */
public final static int CONSTRUCTOR= 0x200;
private ImageDescriptor fBaseImage;
private int fFlags;
private Point fSize;
/**
* Creates a new JavaElementImageDescriptor.
*
* @param baseImage an image descriptor used as the base image
* @param flags flags indicating which adornments are to be rendered. See <code>setAdornments</code>
* for valid values.
* @param size the size of the resulting image
* @see #setAdornments(int)
*/
public JavaElementImageDescriptor(ImageDescriptor baseImage, int flags, Point size) {
fBaseImage= baseImage;
Assert.isNotNull(fBaseImage);
fFlags= flags;
Assert.isTrue(fFlags >= 0);
fSize= size;
Assert.isNotNull(fSize);
}
/**
* Sets the descriptors adornments. Valid values are: <code>ABSTRACT</code>, <code>FINAL</code>,
* <code>SYNCHRONIZED</code>, </code>STATIC<code>, </code>RUNNABLE<code>, </code>WARNING<code>,
* </code>ERROR<code>, </code>OVERRIDDES<code>, <code>IMPLEMENTS</code>, <code>CONSTRUCTOR</code>,
* or any combination of those.
*
* @param adornments the image descritpors adornments
*/
public void setAdornments(int adornments) {
Assert.isTrue(adornments >= 0);
fFlags= adornments;
}
/**
* Returns the current adornments.
*
* @return the current adornments
*/
public int getAdronments() {
return fFlags;
}
/**
* Sets the size of the image created by calling <code>createImage()</code>.
*
* @param size the size of the image returned from calling <code>createImage()</code>
* @see ImageDescriptor#createImage()
*/
public void setImageSize(Point size) {
Assert.isNotNull(size);
Assert.isTrue(size.x >= 0 && size.y >= 0);
fSize= size;
}
/**
* Returns the size of the image created by calling <code>createImage()</code>.
*
* @return the size of the image created by calling <code>createImage()</code>
* @see ImageDescriptor#createImage()
*/
public Point getImageSize() {
return new Point(fSize.x, fSize.y);
}
/* (non-Javadoc)
* Method declared in CompositeImageDescriptor
*/
protected Point getSize() {
return fSize;
}
/* (non-Javadoc)
* Method declared on Object.
*/
public boolean equals(Object object) {
if (!JavaElementImageDescriptor.class.equals(object.getClass()))
return false;
JavaElementImageDescriptor other= (JavaElementImageDescriptor)object;
return (fBaseImage.equals(other.fBaseImage) && fFlags == other.fFlags && fSize.equals(other.fSize));
}
/* (non-Javadoc)
* Method declared on Object.
*/
public int hashCode() {
return fBaseImage.hashCode() | fFlags | fSize.hashCode();
}
/* (non-Javadoc)
* Method declared in CompositeImageDescriptor
*/
protected void drawCompositeImage(int width, int height) {
ImageData bg;
if ((bg= fBaseImage.getImageData()) == null)
bg= DEFAULT_IMAGE_DATA;
drawImage(bg, 0, 0);
drawTopRight();
drawBottomRight();
drawBottomLeft();
}
private void drawTopRight() {
int x= getSize().x;
ImageData data= null;
if ((fFlags & ABSTRACT) != 0) {
data= JavaPluginImages.DESC_OVR_ABSTRACT.getImageData();
x-= data.width;
drawImage(data, x, 0);
}
if ((fFlags & CONSTRUCTOR) != 0) {
data= JavaPluginImages.DESC_OVR_CONSTRUCTOR.getImageData();
x-= data.width;
drawImage(data, x, 0);
}
if ((fFlags & FINAL) != 0) {
data= JavaPluginImages.DESC_OVR_FINAL.getImageData();
x-= data.width;
drawImage(data, x, 0);
}
if ((fFlags & STATIC) != 0) {
data= JavaPluginImages.DESC_OVR_STATIC.getImageData();
x-= data.width;
drawImage(data, x, 0);
}
}
private void drawBottomRight() {
Point size= getSize();
int x= size.x;
ImageData data= null;
if ((fFlags & OVERRIDES) != 0) {
data= JavaPluginImages.DESC_OVR_OVERRIDES.getImageData();
x-= data.width;
drawImage(data, x, size.y - data.height);
}
if ((fFlags & IMPLEMENTS) != 0) {
data= JavaPluginImages.DESC_OVR_IMPLEMENTS.getImageData();
x-= data.width;
drawImage(data, x, size.y - data.height);
}
if ((fFlags & SYNCHRONIZED) != 0) {
data= JavaPluginImages.DESC_OVR_SYNCH.getImageData();
x-= data.width;
drawImage(data, x, size.y - data.height);
}
if ((fFlags & RUNNABLE) != 0) {
data= JavaPluginImages.DESC_OVR_RUN.getImageData();
x-= data.width;
drawImage(data, x, size.y - data.height);
}
}
private void drawBottomLeft() {
Point size= getSize();
int x= 0;
ImageData data= null;
if ((fFlags & ERROR) != 0) {
data= JavaPluginImages.DESC_OVR_ERROR.getImageData();
drawImage(data, x, size.y - data.height);
x+= data.width;
}
if ((fFlags & WARNING) != 0) {
data= JavaPluginImages.DESC_OVR_WARNING.getImageData();
drawImage(data, x, size.y - data.height);
x+= data.width;
}
}
}
|
32,897 |
Bug 32897 Cannot configure Javadoc referenced classes
|
In the second step of the Generate Javadoc wizard, I should be able to configure referenced classes. For example, JUnit is listed in the listbox. If I try to configure it and enter a URL for it (which is correctly validated), the OK button of that dialog does not work; only the cancel button does!
|
resolved fixed
|
9a27494
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T22:02:06Z | 2003-02-25T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocStandardWizardPage.java
| |
32,902 |
Bug 32902 No "delete" QF available for import of non-existing package [code manipulation]
|
I20030221 (RC1) - add import declaration to non-existing package to any java source (or remove a package from your project so that you have bogus imports) Observe: you don't get a "remove" QuickFix
|
resolved fixed
|
0864a7f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-27T22:29:05Z | 2003-02-25T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java
|
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.compiler.IProblem;
/**
*/
public class QuickFixProcessor implements ICorrectionProcessor {
public static boolean hasCorrections(int problemId) {
switch (problemId) {
case IProblem.UnterminatedString:
case IProblem.UnusedImport:
case IProblem.DuplicateImport:
case IProblem.CannotImportPackage:
case IProblem.ConflictingImport:
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.MethodRequiresBody:
case IProblem.NeedToEmulateFieldReadAccess:
case IProblem.NeedToEmulateFieldWriteAccess:
case IProblem.NeedToEmulateMethodAccess:
case IProblem.NeedToEmulateConstructorAccess:
return true;
default:
return false;
}
}
public void process(ICorrectionContext context, List proposals) throws CoreException {
int id= context.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= InsertCorrectionProposal.moveBack(context.getOffset() + context.getLength(), context.getOffset(), "\n\r", context.getCompilationUnit()); //$NON-NLS-1$
proposals.add(new InsertCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, "\"", 0)); //$NON-NLS-1$
break;
case IProblem.UnusedImport:
case IProblem.DuplicateImport:
case IProblem.CannotImportPackage:
case IProblem.ConflictingImport:
ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, proposals);
break;
case IProblem.UndefinedMethod:
UnresolvedElementsSubProcessor.getMethodProposals(context, false, proposals);
break;
case IProblem.UndefinedConstructor:
UnresolvedElementsSubProcessor.getConstructorProposals(context, proposals);
break;
case IProblem.ParameterMismatch:
UnresolvedElementsSubProcessor.getMethodProposals(context, true, proposals);
break;
case IProblem.MethodButWithConstructorName:
ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, proposals);
break;
case IProblem.UndefinedField:
case IProblem.UndefinedName:
UnresolvedElementsSubProcessor.getVariableProposals(context, proposals);
break;
case IProblem.FieldTypeAmbiguous:
case IProblem.ArgumentTypeAmbiguous:
case IProblem.ExceptionTypeAmbiguous:
case IProblem.ReturnTypeAmbiguous:
case IProblem.SuperclassAmbiguous:
case IProblem.InterfaceAmbiguous:
case IProblem.AmbiguousType:
UnresolvedElementsSubProcessor.getAmbiguosTypeReferenceProposals(context, proposals);
break;
case IProblem.PublicClassMustMatchFileName:
ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(context, proposals);
break;
case IProblem.PackageIsNotExpectedPackage:
ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(context, proposals);
break;
case IProblem.UndefinedType:
case IProblem.FieldTypeNotFound:
case IProblem.ArgumentTypeNotFound:
case IProblem.ReturnTypeNotFound:
case IProblem.SuperclassNotFound:
case IProblem.ExceptionTypeNotFound:
case IProblem.InterfaceNotFound:
UnresolvedElementsSubProcessor.getTypeProposals(context, proposals);
break;
case IProblem.TypeMismatch:
LocalCorrectionsSubProcessor.addCastProposals(context, proposals);
break;
case IProblem.UnhandledException:
LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, proposals);
break;
case IProblem.UnreachableCatch:
LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, proposals);
break;
case IProblem.VoidMethodReturnsValue:
ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, proposals);
break;
case IProblem.MissingReturnType:
ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, proposals);
break;
case IProblem.ShouldReturnValue:
ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, proposals);
break;
case IProblem.NonExternalizedStringLiteral:
LocalCorrectionsSubProcessor.addNLSProposals(context, proposals);
break;
case IProblem.NonStaticAccessToStaticField:
case IProblem.NonStaticAccessToStaticMethod:
LocalCorrectionsSubProcessor.addInstanceAccessToStaticProposals(context, proposals);
break;
case IProblem.StaticMethodRequested:
case IProblem.NonStaticFieldFromStaticInvocation:
case IProblem.InstanceMethodDuringConstructorInvocation:
case IProblem.InstanceFieldDuringConstructorInvocation:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, ModifierCorrectionSubProcessor.TO_STATIC);
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:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE);
break;
case IProblem.BodyForAbstractMethod:
case IProblem.AbstractMethodInAbstractClass:
ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, proposals);
break;
case IProblem.AbstractMethodMustBeImplemented:
LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, proposals);
break;
case IProblem.BodyForNativeMethod:
ModifierCorrectionSubProcessor.addNativeMethodProposals(context, proposals);
break;
case IProblem.MethodRequiresBody:
ModifierCorrectionSubProcessor.addMethodRequiresBodyProposals(context, proposals);
break;
case IProblem.OuterLocalMustBeFinal:
ModifierCorrectionSubProcessor.addNonFinalLocalProposal(context, proposals);
break;
case IProblem.UninitializedLocalVariable:
LocalCorrectionsSubProcessor.addUninitializedLocalVariableProposal(context, proposals);
break;
case IProblem.UnhandledExceptionInDefaultConstructor:
case IProblem.UndefinedConstructorInDefaultConstructor:
case IProblem.NotVisibleConstructorInDefaultConstructor:
LocalCorrectionsSubProcessor.addConstructorFromSuperclassProposal(context, proposals);
break;
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateConstructor:
case IProblem.UnusedPrivateField:
case IProblem.UnusedPrivateType:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, proposals);
break;
case IProblem.NeedToEmulateFieldReadAccess:
case IProblem.NeedToEmulateFieldWriteAccess:
case IProblem.NeedToEmulateMethodAccess:
case IProblem.NeedToEmulateConstructorAccess:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, ModifierCorrectionSubProcessor.TO_NON_PRIVATE);
break;
default:
}
}
}
|
33,518 |
Bug 33518 Label of "New Classpath Entry" dialog doesn't show banded background
|
I2003-02-27 The "New Classpath Entry" dialog contains a label that is supposed to display some status information. On MacOS X, the label is display with either white or gray background. However, there should be no colored background instead the common OSX background should show through.
|
resolved fixed
|
3005c42
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T10:08:13Z | 2003-02-28T08:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/MessageLine.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
* A message line displaying a status.
*/
public class MessageLine extends CLabel {
private static final RGB ERROR_BACKGROUND_RGB = new RGB(230, 226, 221);
private Color fNormalMsgAreaBackground;
private Color fErrorMsgAreaBackground;
/**
* Creates a new message line as a child of the given parent.
*/
public MessageLine(Composite parent) {
this(parent, SWT.LEFT);
}
/**
* Creates a new message line as a child of the parent and with the given SWT stylebits.
*/
public MessageLine(Composite parent, int style) {
super(parent, style);
fNormalMsgAreaBackground= getBackground();
fErrorMsgAreaBackground= null;
}
private Image findImage(IStatus status) {
if (status.isOK()) {
return null;
} else if (status.matches(IStatus.ERROR)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_ERROR);
} else if (status.matches(IStatus.WARNING)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_WARNING);
} else if (status.matches(IStatus.INFO)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_INFO);
}
return null;
}
/**
* Sets the message and image to the given status.
* <code>null</code> is a valid argument and will set the empty text and no image
*/
public void setErrorStatus(IStatus status) {
if (status != null) {
String message= status.getMessage();
if (message != null && message.length() > 0) {
setText(message);
setImage(findImage(status));
if (fErrorMsgAreaBackground == null) {
fErrorMsgAreaBackground= new Color(getDisplay(), ERROR_BACKGROUND_RGB);
}
setBackground(fErrorMsgAreaBackground);
return;
}
}
setText(""); //$NON-NLS-1$
setImage(null);
setBackground(fNormalMsgAreaBackground);
}
/*
* @see Widget#dispose()
*/
public void dispose() {
if (fErrorMsgAreaBackground != null) {
fErrorMsgAreaBackground.dispose();
fErrorMsgAreaBackground= null;
}
super.dispose();
}
}
|
33,020 |
Bug 33020 Have to get rid of cell editors and table cursor
| null |
resolved fixed
|
cad9430
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T11:20:20Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui
| |
33,020 |
Bug 33020 Have to get rid of cell editors and table cursor
| null |
resolved fixed
|
cad9430
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T11:20:20Z | 2003-02-25T16:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeParametersControl.java
| |
33,020 |
Bug 33020 Have to get rid of cell editors and table cursor
| null |
resolved fixed
|
cad9430
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T11:20:20Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui
| |
33,020 |
Bug 33020 Have to get rid of cell editors and table cursor
| null |
resolved fixed
|
cad9430
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T11:20:20Z | 2003-02-25T16:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ParameterEditDialog.java
| |
33,376 |
Bug 33376 Move Inner Type to Top Level: Error dialog layouted wrong
|
RC1 1. Create a class with an inner class, make the file read-only 2. Select the name of the inner class, choose 'Move Inner Type to Top Level' 3. error dialog that shows up is strangely layouted. see screenshot
|
resolved fixed
|
de309d6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T13:37:24Z | 2003-02-26T22:53:20Z |
org.eclipse.jdt.ui/ui
| |
33,376 |
Bug 33376 Move Inner Type to Top Level: Error dialog layouted wrong
|
RC1 1. Create a class with an inner class, make the file read-only 2. Select the name of the inner class, choose 'Move Inner Type to Top Level' 3. error dialog that shows up is strangely layouted. see screenshot
|
resolved fixed
|
de309d6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T13:37:24Z | 2003-02-26T22:53:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringStatusViewer.java
| |
32,431 |
Bug 32431 extract method: extracted method should be private, not public [refactoring]
|
Currently, the default protection level of an extracted method is 'public'. This is a 'worst practice' of object-oriented programming, since it would violate encapsulation by introducing a method into the class' public API. The default selection should be 'private'. Or at least be settable.
|
resolved fixed
|
d34e55d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T14:04:47Z | 2003-02-21T01:13:20Z |
org.eclipse.jdt.ui/core
| |
32,431 |
Bug 32431 extract method: extracted method should be private, not public [refactoring]
|
Currently, the default protection level of an extracted method is 'public'. This is a 'worst practice' of object-oriented programming, since it would violate encapsulation by introducing a method into the class' public API. The default selection should be 'private'. Or at least be settable.
|
resolved fixed
|
d34e55d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T14:04:47Z | 2003-02-21T01:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
| |
33,029 |
Bug 33029 Refactoring preview dialog positioned outside screen
|
RC1 - activate a refactoring - move dialog to bottom of screen - press preview Observe: dialog gets resized. It is positioned in a way that the buttons are no longer accessable.
|
resolved fixed
|
df2acb8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T14:18:39Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui
| |
33,029 |
Bug 33029 Refactoring preview dialog positioned outside screen
|
RC1 - activate a refactoring - move dialog to bottom of screen - press preview Observe: dialog gets resized. It is positioned in a way that the buttons are no longer accessable.
|
resolved fixed
|
df2acb8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T14:18:39Z | 2003-02-25T16:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringWizardDialog2.java
| |
33,103 |
Bug 33103 Non externalized menu names in JDT UI
|
RC1 There are references to non-externalized names in JDT which show up in the pulldown for the PackageExplorer. They appear to be in: PackagesView.java - org.eclipse.jdt.ui/src- jdt/org/eclipse/jdt/internal/ui/browsing LayoutActionGroup.java - org.eclipse.jdt.ui/src- jdt/org/eclipse/jdt/internal/ui/packageview
|
resolved fixed
|
949b6ac
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T14:43:30Z | 2003-02-25T19:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/PackagesView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.jdt.core.IClassFile;
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.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
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.MultiActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.filters.NonJavaElementFilter;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
public class PackagesView extends JavaBrowsingPart{
private static final String TAG_VIEW_STATE= ".viewState"; //$NON-NLS-1$
private static final int LIST_VIEW_STATE= 0;
private static final int TREE_VIEW_STATE= 1;
private static class StatusBarUpdater4LogicalPackage extends StatusBarUpdater {
private StatusBarUpdater4LogicalPackage(IStatusLineManager statusLineManager) {
super(statusLineManager);
}
protected String formatMessage(ISelection sel) {
if (sel instanceof IStructuredSelection) {
IStructuredSelection selection= (IStructuredSelection)sel;
int nElements= selection.size();
Object elem= selection.getFirstElement();
if (nElements == 1 && (elem instanceof LogicalPackage))
return formatLogicalPackageMessage((LogicalPackage) elem);
}
return super.formatMessage(sel);
}
private String formatLogicalPackageMessage(LogicalPackage logicalPackage) {
IPackageFragment[] fragments= logicalPackage.getFragments();
StringBuffer buf= new StringBuffer(logicalPackage.getElementName());
buf.append(JavaElementLabels.CONCAT_STRING);
String message= ""; //$NON-NLS-1$
boolean firstTime= true;
for (int i= 0; i < fragments.length; i++) {
IPackageFragment fragment= fragments[i];
IJavaElement element= fragment.getParent();
if (element instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) element;
String label= JavaElementLabels.getElementLabel(root, JavaElementLabels.DEFAULT_QUALIFIED | JavaElementLabels.ROOT_QUALIFIED);
if (firstTime) {
buf.append(label);
firstTime= false;
}
else
message= JavaBrowsingMessages.getFormattedString("StatusBar.concat", new String[] {message, label}); //$NON-NLS-1$
}
}
buf.append(message);
return buf.toString();
}
};
private SelectAllAction fSelectAllAction;
private int fCurrViewState;
private PackageViewerWrapper fWrappedViewer;
private MultiActionGroup fSwitchActionGroup;
private boolean fLastInputWasProject;
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
super.addFilters();
getViewer().addFilter(createNonJavaElementFilter());
getViewer().addFilter(new LibraryFilter());
}
/**
* Creates new NonJavaElementFilter and overides method select to allow for
* LogicalPackages.
* @return NonJavaElementFilter
*/
protected NonJavaElementFilter createNonJavaElementFilter() {
return new NonJavaElementFilter(){
public boolean select(Viewer viewer, Object parent, Object element){
return ((element instanceof IJavaElement) || (element instanceof LogicalPackage));
}
};
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
//this must be created before all actions and filters
fWrappedViewer= new PackageViewerWrapper();
restoreLayoutState(memento);
}
private void restoreLayoutState(IMemento memento) {
if (memento == null) {
//read state from the preference store
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
fCurrViewState= store.getInt(this.getViewSite().getId() + TAG_VIEW_STATE);
} else {
//restore from memento
Integer integer= memento.getInteger(this.getViewSite().getId() + TAG_VIEW_STATE);
if ((integer == null) || !isValidState(integer.intValue())) {
fCurrViewState= LIST_VIEW_STATE;
} else fCurrViewState= integer.intValue();
}
}
private boolean isValidState(int state) {
return (state==LIST_VIEW_STATE) || (state==TREE_VIEW_STATE);
}
/*
* @see org.eclipse.ui.IViewPart#saveState(org.eclipse.ui.IMemento)
*/
public void saveState(IMemento memento) {
super.saveState(memento);
memento.putInteger(this.getViewSite().getId()+TAG_VIEW_STATE,fCurrViewState);
}
/**
* Creates the viewer of this part dependent on the current
* layout.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
StructuredViewer viewer;
if(isInListState())
viewer= createTableViewer(parent);
else
viewer= createTreeViewer(parent);
((PackageViewerWrapper)fWrappedViewer).setViewer(viewer);
return fWrappedViewer;
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
protected boolean isInListState() {
return fCurrViewState== LIST_VIEW_STATE;
}
private ProblemTableViewer createTableViewer(Composite parent) {
return new PackagesViewTableViewer(parent, SWT.MULTI);
}
private ProblemTreeViewer createTreeViewer(Composite parent) {
return new PackagesViewTreeViewer(parent, SWT.MULTI);
}
/**
* Overrides the createContentProvider from JavaBrowsingPart
* Creates the the content provider of this part.
*/
protected IContentProvider createContentProvider() {
if(isInListState())
return new PackagesViewFlatContentProvider(fWrappedViewer.getViewer());
else return new PackagesViewHierarchicalContentProvider(fWrappedViewer.getViewer());
}
protected JavaUILabelProvider createLabelProvider() {
if(isInListState())
return createListLabelProvider();
else return createTreeLabelProvider();
}
private JavaUILabelProvider createTreeLabelProvider() {
return new PackagesViewLabelProvider(PackagesViewLabelProvider.HIERARCHICAL_VIEW_STATE);
}
private JavaUILabelProvider createListLabelProvider() {
return new PackagesViewLabelProvider(PackagesViewLabelProvider.FLAT_VIEW_STATE);
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
protected String getHelpContextId() {
return IJavaHelpContextIds.PACKAGES_BROWSING_VIEW;
}
protected String getLinkToEditorKey() {
return PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR;
}
/**
* 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
*/
protected boolean isValidInput(Object element) {
if (element instanceof IJavaProject || (element instanceof IPackageFragmentRoot && ((IJavaElement)element).getElementName() != IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH))
try {
IJavaProject jProject= ((IJavaElement)element).getJavaProject();
if (jProject != null)
return jProject.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
return false;
}
return false;
}
/**
* 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 instanceof IPackageFragment) {
IJavaElement parent= ((IPackageFragment)element).getParent();
if (parent != null)
return super.isValidElement(parent) || super.isValidElement(parent.getJavaProject());
}
return false;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
protected IJavaElement findElementToSelect(IJavaElement je) {
if (je == null)
return null;
switch (je.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
return je;
case IJavaElement.COMPILATION_UNIT:
return ((ICompilationUnit)je).getParent();
case IJavaElement.CLASS_FILE:
return ((IClassFile)je).getParent();
case IJavaElement.TYPE:
return ((IType)je).getPackageFragment();
default:
return findElementToSelect(je.getParent());
}
}
/*
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#setInput(java.lang.Object)
*/
protected void setInput(Object input) {
setViewerWrapperInput(input);
super.updateTitle();
}
private void setViewerWrapperInput(Object input) {
fWrappedViewer.setViewerInput(input);
}
/**
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#fillActionBars(org.eclipse.ui.IActionBars)
*/
protected void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
fSwitchActionGroup.fillActionBars(actionBars);
}
private void setUpViewer(StructuredViewer viewer){
Assert.isTrue(viewer != null);
JavaUILabelProvider labelProvider= createLabelProvider();
viewer.setLabelProvider(createDecoratingLabelProvider(labelProvider));
viewer.setSorter(createJavaElementSorter());
viewer.setUseHashlookup(true);
createContextMenu();
//disapears when control disposed
addKeyListener();
//this methods only adds listeners to the viewer,
//these listenters disapear when the viewer is disposed
hookViewerListeners();
// Set content provider
viewer.setContentProvider(createContentProvider());
//Disposed when viewer's Control is disposed
initDragAndDrop();
}
//alter sorter to include LogicalPackages
protected JavaElementSorter createJavaElementSorter() {
return new JavaElementSorter(){
public int category(Object element) {
if (element instanceof LogicalPackage) {
LogicalPackage cp= (LogicalPackage) element;
return super.category(cp.getFragments()[0]);
} else return super.category(element);
}
public int compare(Viewer viewer, Object e1, Object e2){
if (e1 instanceof LogicalPackage) {
LogicalPackage cp= (LogicalPackage) e1;
e1= cp.getFragments()[0];
}
if (e2 instanceof LogicalPackage) {
LogicalPackage cp= (LogicalPackage) e2;
e2= cp.getFragments()[0];
}
return super.compare(viewer, e1, e2);
}
};
}
protected StatusBarUpdater createStatusBarUpdater(IStatusLineManager slManager) {
return new StatusBarUpdater4LogicalPackage(slManager);
}
protected void setSiteSelectionProvider(){
getSite().setSelectionProvider(fWrappedViewer);
}
void adjustInputAndSetSelection(Object o) {
if (!(o instanceof LogicalPackage)) {
super.adjustInputAndSetSelection(o);
return;
}
LogicalPackage lp= (LogicalPackage)o;
if (!lp.getJavaProject().equals(getInput()))
setInput(lp.getJavaProject());
setSelection(new StructuredSelection(lp), true);
}
//do the same thing as the JavaBrowsingPart but with wrapper
protected void createActions() {
super.createActions();
createSelectAllAction();
//create the switch action group
fSwitchActionGroup= createSwitchActionGroup();
}
private MultiActionGroup createSwitchActionGroup(){
LayoutAction switchToFlatViewAction= new LayoutAction(JavaBrowsingMessages.getString("PackagesView.flatLayoutAction.label"),LIST_VIEW_STATE); //$NON-NLS-1$
LayoutAction switchToHierarchicalViewAction= new LayoutAction(JavaBrowsingMessages.getString("PackagesView.HierarchicalLayoutAction.label"), TREE_VIEW_STATE); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(switchToFlatViewAction, "flatLayout.gif"); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(switchToHierarchicalViewAction, "hierarchicalLayout.gif"); //$NON-NLS-1$
return new LayoutActionGroup(new IAction[]{switchToFlatViewAction,switchToHierarchicalViewAction}, fCurrViewState);
}
private static class LayoutActionGroup extends MultiActionGroup {
LayoutActionGroup(IAction[] actions, int index) {
super(actions, index);
}
public void fillActionBars(IActionBars actionBars) {
//create new layout group
IMenuManager manager= actionBars.getMenuManager();
IContributionItem groupMarker= new GroupMarker("Layout"); //$NON-NLS-1$
manager.add(groupMarker);
IMenuManager newManager= new MenuManager(JavaBrowsingMessages.getString("PackagesView.LayoutActionGroup.layout.label")); //$NON-NLS-1$
manager.appendToGroup("Layout", newManager); //$NON-NLS-1$
super.addActions(newManager);
}
}
/**
* Switches between flat and hierarchical state.
*/
private class LayoutAction extends Action {
private int fState;
private Runnable fRunnable;
public LayoutAction(String text, int state) {
super(text);
fState= state;
}
public int getState() {
return fState;
}
public void setRunnable(Runnable runnable) {
Assert.isNotNull(runnable);
fRunnable= runnable;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
switchViewer(fState);
}
}
private void switchViewer(int state) {
//Indicate which viewer is to be used
if (fCurrViewState == state)
return;
else {
fCurrViewState= state;
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(getViewSite().getId() + TAG_VIEW_STATE, state);
}
//get the information from the existing viewer
StructuredViewer viewer= fWrappedViewer.getViewer();
Object object= viewer.getInput();
ISelection selection= viewer.getSelection();
// create and set up the new viewer
Control control= createViewer(fWrappedViewer.getControl().getParent()).getControl();
setUpViewer(fWrappedViewer);
createSelectAllAction();
// add the selection information from old viewer
fWrappedViewer.setViewerInput(object);
fWrappedViewer.setSelection(selection, true);
// dispose old viewer
viewer.getContentProvider().dispose();
viewer.getControl().dispose();
// layout the new viewer
if (control != null && !control.isDisposed()) {
control.setVisible(true);
control.getParent().layout(true);
}
}
private void createSelectAllAction() {
IActionBars actionBars= getViewSite().getActionBars();
if (isInListState()) {
fSelectAllAction= new SelectAllAction((TableViewer)fWrappedViewer.getViewer());
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
} else {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, null);
fSelectAllAction= null;
}
actionBars.updateActionBars();
}
protected IJavaElement findInputForJavaElement(IJavaElement je) {
if(je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT || je.getElementType() == IJavaElement.JAVA_PROJECT)
return findInputForJavaElement(je, true);
else
return findInputForJavaElement(je, false);
}
protected IJavaElement findInputForJavaElement(IJavaElement je, boolean canChangeInputType) {
if (je == null || !je.exists())
return null;
if (isValidInput(je)) {
//don't update if input must be project (i.e. project is used as source folder)
if (canChangeInputType)
fLastInputWasProject= je.getElementType() == IJavaElement.JAVA_PROJECT;
return je;
} else if (fLastInputWasProject) {
IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot)je.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (!packageFragmentRoot.isExternal())
return je.getJavaProject();
}
return findInputForJavaElement(je.getParent(), canChangeInputType);
}
/**
* Override the getText and getImage methods for the DecoratingLabelProvider
* to handel the decoration of logical packages.
*
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#createDecoratingLabelProvider(org.eclipse.jface.viewers.ILabelDecorator)
*/
protected DecoratingLabelProvider createDecoratingLabelProvider(JavaUILabelProvider provider) {
return new DecoratingJavaLabelProvider(provider, false, false) {
public String getText(Object element){
if (element instanceof LogicalPackage) {
LogicalPackage el= (LogicalPackage) element;
return super.getText(el.getFragments()[0]);
} else return super.getText(element);
}
public Image getImage(Object element) {
if(element instanceof LogicalPackage){
LogicalPackage el= (LogicalPackage) element;
ILabelDecorator decorator= getLabelDecorator();
IPackageFragment[] fragments= el.getFragments();
Image image= super.getImage(el);
for (int i= 0; i < fragments.length; i++) {
IPackageFragment fragment= fragments[i];
Image decoratedImage= decorator.decorateImage(image, fragment);
if(decoratedImage != null)
image= decoratedImage;
}
return image;
} else return super.getImage(element);
}
};
}
/*
* Overridden from JavaBrowsingPart to handel LogicalPackages and tree
* structure.
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#adjustInputAndSetSelection(org.eclipse.jdt.core.IJavaElement)
*/
void adjustInputAndSetSelection(IJavaElement je) {
IJavaElement jElementToSelect= getSuitableJavaElement(findElementToSelect(je));
LogicalPackagesProvider p= (LogicalPackagesProvider) fWrappedViewer.getContentProvider();
Object elementToSelect= jElementToSelect;
if (jElementToSelect != null && jElementToSelect.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
IPackageFragment pkgFragment= (IPackageFragment)jElementToSelect;
elementToSelect= p.findLogicalPackage(pkgFragment);
if (elementToSelect == null)
elementToSelect= pkgFragment;
}
IJavaElement newInput= findInputForJavaElement(je);
if (elementToSelect == null && !isValidInput(newInput))
setInput(null);
else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) {
//optimization, if you are in the same project but expansion hasn't happened
Object input= getViewer().getInput();
if (elementToSelect != null && newInput != null) {
if (newInput.equals(input)) {
getViewer().reveal(elementToSelect);
// Adjust input to selection
} else {
setInput(newInput);
getViewer().reveal(elementToSelect);
}
} else
setInput(newInput);
// Recompute suitable element since it depends on the viewer's input
jElementToSelect= getSuitableJavaElement(elementToSelect);
if (jElementToSelect != null && jElementToSelect.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
IPackageFragment pkgFragment= (IPackageFragment)jElementToSelect;
elementToSelect= p.findLogicalPackage(pkgFragment);
if (elementToSelect == null)
elementToSelect= pkgFragment;
}
}
ISelection selection;
if (elementToSelect != null)
selection= new StructuredSelection(elementToSelect);
else
selection= StructuredSelection.EMPTY;
setSelection(selection, true);
}
}
|
33,103 |
Bug 33103 Non externalized menu names in JDT UI
|
RC1 There are references to non-externalized names in JDT which show up in the pulldown for the PackageExplorer. They appear to be in: PackagesView.java - org.eclipse.jdt.ui/src- jdt/org/eclipse/jdt/internal/ui/browsing LayoutActionGroup.java - org.eclipse.jdt.ui/src- jdt/org/eclipse/jdt/internal/ui/packageview
|
resolved fixed
|
949b6ac
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T14:43:30Z | 2003-02-25T19:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/LayoutActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import org.eclipse.jface.action.Action;
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.IWorkbenchActionConstants;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.MultiActionGroup;
/**
* Adds view menus to switch between flat and hierarchical layout.
*
* @since 2.1
*/
class LayoutActionGroup extends MultiActionGroup {
LayoutActionGroup(PackageExplorerPart packageExplorer) {
super(createActions(packageExplorer), getSelectedState(packageExplorer));
}
/* (non-Javadoc)
* @see ActionGroup#fillActionBars(IActionBars)
*/
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
contributeToViewMenu(actionBars.getMenuManager());
}
private void contributeToViewMenu(IMenuManager viewMenu) {
viewMenu.add(new Separator());
// Create layout sub menu
IMenuManager layoutSubMenu= new MenuManager("Layout"); //$NON-NLS-1$
String layoutGroupName= PackagesMessages.getString("LayoutActionGroup.label"); //$NON-NLS-1$
// GroupMarker marker= new GroupMarker(layoutGroupName);
Separator marker= new Separator(layoutGroupName);
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
viewMenu.add(marker);
viewMenu.appendToGroup(layoutGroupName,layoutSubMenu);
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
addActions(layoutSubMenu);
}
static int getSelectedState(PackageExplorerPart packageExplorer) {
if (packageExplorer.isFlatLayout())
return 0;
else
return 1;
}
static IAction[] createActions(PackageExplorerPart packageExplorer) {
IAction flatLayoutAction= new LayoutAction(packageExplorer, true);
flatLayoutAction.setText(PackagesMessages.getString("LayoutActionGroup.flatLayoutAction.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(flatLayoutAction, "flatLayout.gif"); //$NON-NLS-1$
IAction hierarchicalLayout= new LayoutAction(packageExplorer, false);
hierarchicalLayout.setText(PackagesMessages.getString("LayoutActionGroup.hierarchicalLayoutAction.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(hierarchicalLayout, "hierarchicalLayout.gif"); //$NON-NLS-1$
return new IAction[]{flatLayoutAction, hierarchicalLayout};
}
}
class LayoutAction extends Action implements IAction {
private boolean fIsFlatLayout;
private PackageExplorerPart fPackageExplorer;
public LayoutAction(PackageExplorerPart packageExplorer, boolean state) {
fIsFlatLayout= state;
fPackageExplorer= packageExplorer;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
if (fPackageExplorer.isFlatLayout() != fIsFlatLayout)
fPackageExplorer.toggleLayout();
}
}
|
32,714 |
Bug 32714 Packages View: flickering and loosing expanded state when logical package is selected with hierarchical layout
|
In the java browsing perspective: - enable hierarchical layout for the packages view - select a logical package in the packages view - select types/methods in the types/methods views -> the packages view flickers and looses the expanded state (the tree is only expanded upto the logical package, other expanded subtrees are collapsed)
|
resolved wontfix
|
7cb9c3d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T16:03:24Z | 2003-02-24T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/PackagesView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.jdt.core.IClassFile;
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.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
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.MultiActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.filters.NonJavaElementFilter;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
public class PackagesView extends JavaBrowsingPart{
private static final String TAG_VIEW_STATE= ".viewState"; //$NON-NLS-1$
private static final int LIST_VIEW_STATE= 0;
private static final int TREE_VIEW_STATE= 1;
private static class StatusBarUpdater4LogicalPackage extends StatusBarUpdater {
private StatusBarUpdater4LogicalPackage(IStatusLineManager statusLineManager) {
super(statusLineManager);
}
protected String formatMessage(ISelection sel) {
if (sel instanceof IStructuredSelection) {
IStructuredSelection selection= (IStructuredSelection)sel;
int nElements= selection.size();
Object elem= selection.getFirstElement();
if (nElements == 1 && (elem instanceof LogicalPackage))
return formatLogicalPackageMessage((LogicalPackage) elem);
}
return super.formatMessage(sel);
}
private String formatLogicalPackageMessage(LogicalPackage logicalPackage) {
IPackageFragment[] fragments= logicalPackage.getFragments();
StringBuffer buf= new StringBuffer(logicalPackage.getElementName());
buf.append(JavaElementLabels.CONCAT_STRING);
String message= ""; //$NON-NLS-1$
boolean firstTime= true;
for (int i= 0; i < fragments.length; i++) {
IPackageFragment fragment= fragments[i];
IJavaElement element= fragment.getParent();
if (element instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) element;
String label= JavaElementLabels.getElementLabel(root, JavaElementLabels.DEFAULT_QUALIFIED | JavaElementLabels.ROOT_QUALIFIED);
if (firstTime) {
buf.append(label);
firstTime= false;
}
else
message= JavaBrowsingMessages.getFormattedString("StatusBar.concat", new String[] {message, label}); //$NON-NLS-1$
}
}
buf.append(message);
return buf.toString();
}
};
private SelectAllAction fSelectAllAction;
private int fCurrViewState;
private PackageViewerWrapper fWrappedViewer;
private MultiActionGroup fSwitchActionGroup;
private boolean fLastInputWasProject;
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
super.addFilters();
getViewer().addFilter(createNonJavaElementFilter());
getViewer().addFilter(new LibraryFilter());
}
/**
* Creates new NonJavaElementFilter and overides method select to allow for
* LogicalPackages.
* @return NonJavaElementFilter
*/
protected NonJavaElementFilter createNonJavaElementFilter() {
return new NonJavaElementFilter(){
public boolean select(Viewer viewer, Object parent, Object element){
return ((element instanceof IJavaElement) || (element instanceof LogicalPackage));
}
};
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
//this must be created before all actions and filters
fWrappedViewer= new PackageViewerWrapper();
restoreLayoutState(memento);
}
private void restoreLayoutState(IMemento memento) {
if (memento == null) {
//read state from the preference store
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
fCurrViewState= store.getInt(this.getViewSite().getId() + TAG_VIEW_STATE);
} else {
//restore from memento
Integer integer= memento.getInteger(this.getViewSite().getId() + TAG_VIEW_STATE);
if ((integer == null) || !isValidState(integer.intValue())) {
fCurrViewState= LIST_VIEW_STATE;
} else fCurrViewState= integer.intValue();
}
}
private boolean isValidState(int state) {
return (state==LIST_VIEW_STATE) || (state==TREE_VIEW_STATE);
}
/*
* @see org.eclipse.ui.IViewPart#saveState(org.eclipse.ui.IMemento)
*/
public void saveState(IMemento memento) {
super.saveState(memento);
memento.putInteger(this.getViewSite().getId()+TAG_VIEW_STATE,fCurrViewState);
}
/**
* Creates the viewer of this part dependent on the current
* layout.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
StructuredViewer viewer;
if(isInListState())
viewer= createTableViewer(parent);
else
viewer= createTreeViewer(parent);
((PackageViewerWrapper)fWrappedViewer).setViewer(viewer);
return fWrappedViewer;
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
protected boolean isInListState() {
return fCurrViewState== LIST_VIEW_STATE;
}
private ProblemTableViewer createTableViewer(Composite parent) {
return new PackagesViewTableViewer(parent, SWT.MULTI);
}
private ProblemTreeViewer createTreeViewer(Composite parent) {
return new PackagesViewTreeViewer(parent, SWT.MULTI);
}
/**
* Overrides the createContentProvider from JavaBrowsingPart
* Creates the the content provider of this part.
*/
protected IContentProvider createContentProvider() {
if(isInListState())
return new PackagesViewFlatContentProvider(fWrappedViewer.getViewer());
else return new PackagesViewHierarchicalContentProvider(fWrappedViewer.getViewer());
}
protected JavaUILabelProvider createLabelProvider() {
if(isInListState())
return createListLabelProvider();
else return createTreeLabelProvider();
}
private JavaUILabelProvider createTreeLabelProvider() {
return new PackagesViewLabelProvider(PackagesViewLabelProvider.HIERARCHICAL_VIEW_STATE);
}
private JavaUILabelProvider createListLabelProvider() {
return new PackagesViewLabelProvider(PackagesViewLabelProvider.FLAT_VIEW_STATE);
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
protected String getHelpContextId() {
return IJavaHelpContextIds.PACKAGES_BROWSING_VIEW;
}
protected String getLinkToEditorKey() {
return PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR;
}
/**
* 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
*/
protected boolean isValidInput(Object element) {
if (element instanceof IJavaProject || (element instanceof IPackageFragmentRoot && ((IJavaElement)element).getElementName() != IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH))
try {
IJavaProject jProject= ((IJavaElement)element).getJavaProject();
if (jProject != null)
return jProject.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
return false;
}
return false;
}
/**
* 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 instanceof IPackageFragment) {
IJavaElement parent= ((IPackageFragment)element).getParent();
if (parent != null)
return super.isValidElement(parent) || super.isValidElement(parent.getJavaProject());
}
return false;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
protected IJavaElement findElementToSelect(IJavaElement je) {
if (je == null)
return null;
switch (je.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
return je;
case IJavaElement.COMPILATION_UNIT:
return ((ICompilationUnit)je).getParent();
case IJavaElement.CLASS_FILE:
return ((IClassFile)je).getParent();
case IJavaElement.TYPE:
return ((IType)je).getPackageFragment();
default:
return findElementToSelect(je.getParent());
}
}
/*
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#setInput(java.lang.Object)
*/
protected void setInput(Object input) {
setViewerWrapperInput(input);
super.updateTitle();
}
private void setViewerWrapperInput(Object input) {
fWrappedViewer.setViewerInput(input);
}
/**
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#fillActionBars(org.eclipse.ui.IActionBars)
*/
protected void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
fSwitchActionGroup.fillActionBars(actionBars);
}
private void setUpViewer(StructuredViewer viewer){
Assert.isTrue(viewer != null);
JavaUILabelProvider labelProvider= createLabelProvider();
viewer.setLabelProvider(createDecoratingLabelProvider(labelProvider));
viewer.setSorter(createJavaElementSorter());
viewer.setUseHashlookup(true);
createContextMenu();
//disapears when control disposed
addKeyListener();
//this methods only adds listeners to the viewer,
//these listenters disapear when the viewer is disposed
hookViewerListeners();
// Set content provider
viewer.setContentProvider(createContentProvider());
//Disposed when viewer's Control is disposed
initDragAndDrop();
}
//alter sorter to include LogicalPackages
protected JavaElementSorter createJavaElementSorter() {
return new JavaElementSorter(){
public int category(Object element) {
if (element instanceof LogicalPackage) {
LogicalPackage cp= (LogicalPackage) element;
return super.category(cp.getFragments()[0]);
} else return super.category(element);
}
public int compare(Viewer viewer, Object e1, Object e2){
if (e1 instanceof LogicalPackage) {
LogicalPackage cp= (LogicalPackage) e1;
e1= cp.getFragments()[0];
}
if (e2 instanceof LogicalPackage) {
LogicalPackage cp= (LogicalPackage) e2;
e2= cp.getFragments()[0];
}
return super.compare(viewer, e1, e2);
}
};
}
protected StatusBarUpdater createStatusBarUpdater(IStatusLineManager slManager) {
return new StatusBarUpdater4LogicalPackage(slManager);
}
protected void setSiteSelectionProvider(){
getSite().setSelectionProvider(fWrappedViewer);
}
void adjustInputAndSetSelection(Object o) {
if (!(o instanceof LogicalPackage)) {
super.adjustInputAndSetSelection(o);
return;
}
LogicalPackage lp= (LogicalPackage)o;
if (!lp.getJavaProject().equals(getInput()))
setInput(lp.getJavaProject());
setSelection(new StructuredSelection(lp), true);
}
//do the same thing as the JavaBrowsingPart but with wrapper
protected void createActions() {
super.createActions();
createSelectAllAction();
//create the switch action group
fSwitchActionGroup= createSwitchActionGroup();
}
private MultiActionGroup createSwitchActionGroup(){
LayoutAction switchToFlatViewAction= new LayoutAction(JavaBrowsingMessages.getString("PackagesView.flatLayoutAction.label"),LIST_VIEW_STATE); //$NON-NLS-1$
LayoutAction switchToHierarchicalViewAction= new LayoutAction(JavaBrowsingMessages.getString("PackagesView.HierarchicalLayoutAction.label"), TREE_VIEW_STATE); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(switchToFlatViewAction, "flatLayout.gif"); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(switchToHierarchicalViewAction, "hierarchicalLayout.gif"); //$NON-NLS-1$
return new LayoutActionGroup(new IAction[]{switchToFlatViewAction,switchToHierarchicalViewAction}, fCurrViewState);
}
private static class LayoutActionGroup extends MultiActionGroup {
LayoutActionGroup(IAction[] actions, int index) {
super(actions, index);
}
public void fillActionBars(IActionBars actionBars) {
//create new layout group
IMenuManager manager= actionBars.getMenuManager();
final IContributionItem groupMarker= new GroupMarker("layout"); //$NON-NLS-1$
manager.add(groupMarker);
IMenuManager newManager= new MenuManager(JavaBrowsingMessages.getString("PackagesView.LayoutActionGroup.layout.label")); //$NON-NLS-1$
manager.appendToGroup("layout", newManager); //$NON-NLS-1$
super.addActions(newManager);
}
}
/**
* Switches between flat and hierarchical state.
*/
private class LayoutAction extends Action {
private int fState;
private Runnable fRunnable;
public LayoutAction(String text, int state) {
super(text);
fState= state;
}
public int getState() {
return fState;
}
public void setRunnable(Runnable runnable) {
Assert.isNotNull(runnable);
fRunnable= runnable;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
switchViewer(fState);
}
}
private void switchViewer(int state) {
//Indicate which viewer is to be used
if (fCurrViewState == state)
return;
else {
fCurrViewState= state;
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(getViewSite().getId() + TAG_VIEW_STATE, state);
}
//get the information from the existing viewer
StructuredViewer viewer= fWrappedViewer.getViewer();
Object object= viewer.getInput();
ISelection selection= viewer.getSelection();
// create and set up the new viewer
Control control= createViewer(fWrappedViewer.getControl().getParent()).getControl();
setUpViewer(fWrappedViewer);
createSelectAllAction();
// add the selection information from old viewer
fWrappedViewer.setViewerInput(object);
fWrappedViewer.setSelection(selection, true);
// dispose old viewer
viewer.getContentProvider().dispose();
viewer.getControl().dispose();
// layout the new viewer
if (control != null && !control.isDisposed()) {
control.setVisible(true);
control.getParent().layout(true);
}
}
private void createSelectAllAction() {
IActionBars actionBars= getViewSite().getActionBars();
if (isInListState()) {
fSelectAllAction= new SelectAllAction((TableViewer)fWrappedViewer.getViewer());
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
} else {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, null);
fSelectAllAction= null;
}
actionBars.updateActionBars();
}
protected IJavaElement findInputForJavaElement(IJavaElement je) {
if(je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT || je.getElementType() == IJavaElement.JAVA_PROJECT)
return findInputForJavaElement(je, true);
else
return findInputForJavaElement(je, false);
}
protected IJavaElement findInputForJavaElement(IJavaElement je, boolean canChangeInputType) {
if (je == null || !je.exists())
return null;
if (isValidInput(je)) {
//don't update if input must be project (i.e. project is used as source folder)
if (canChangeInputType)
fLastInputWasProject= je.getElementType() == IJavaElement.JAVA_PROJECT;
return je;
} else if (fLastInputWasProject) {
IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot)je.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (!packageFragmentRoot.isExternal())
return je.getJavaProject();
}
return findInputForJavaElement(je.getParent(), canChangeInputType);
}
/**
* Override the getText and getImage methods for the DecoratingLabelProvider
* to handel the decoration of logical packages.
*
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#createDecoratingLabelProvider(org.eclipse.jface.viewers.ILabelDecorator)
*/
protected DecoratingLabelProvider createDecoratingLabelProvider(JavaUILabelProvider provider) {
return new DecoratingJavaLabelProvider(provider, false, false) {
public String getText(Object element){
if (element instanceof LogicalPackage) {
LogicalPackage el= (LogicalPackage) element;
return super.getText(el.getFragments()[0]);
} else return super.getText(element);
}
public Image getImage(Object element) {
if(element instanceof LogicalPackage){
LogicalPackage el= (LogicalPackage) element;
ILabelDecorator decorator= getLabelDecorator();
IPackageFragment[] fragments= el.getFragments();
Image image= super.getImage(el);
for (int i= 0; i < fragments.length; i++) {
IPackageFragment fragment= fragments[i];
Image decoratedImage= decorator.decorateImage(image, fragment);
if(decoratedImage != null)
image= decoratedImage;
}
return image;
} else return super.getImage(element);
}
};
}
/*
* Overridden from JavaBrowsingPart to handel LogicalPackages and tree
* structure.
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#adjustInputAndSetSelection(org.eclipse.jdt.core.IJavaElement)
*/
void adjustInputAndSetSelection(IJavaElement je) {
IJavaElement jElementToSelect= getSuitableJavaElement(findElementToSelect(je));
LogicalPackagesProvider p= (LogicalPackagesProvider) fWrappedViewer.getContentProvider();
Object elementToSelect= jElementToSelect;
if (jElementToSelect != null && jElementToSelect.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
IPackageFragment pkgFragment= (IPackageFragment)jElementToSelect;
elementToSelect= p.findLogicalPackage(pkgFragment);
if (elementToSelect == null)
elementToSelect= pkgFragment;
}
IJavaElement newInput= findInputForJavaElement(je);
if (elementToSelect == null && !isValidInput(newInput))
setInput(null);
else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) {
//optimization, if you are in the same project but expansion hasn't happened
Object input= getViewer().getInput();
if (elementToSelect != null && newInput != null) {
if (newInput.equals(input)) {
getViewer().reveal(elementToSelect);
// Adjust input to selection
} else {
setInput(newInput);
getViewer().reveal(elementToSelect);
}
} else
setInput(newInput);
// Recompute suitable element since it depends on the viewer's input
jElementToSelect= getSuitableJavaElement(elementToSelect);
if (jElementToSelect != null && jElementToSelect.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
IPackageFragment pkgFragment= (IPackageFragment)jElementToSelect;
elementToSelect= p.findLogicalPackage(pkgFragment);
if (elementToSelect == null)
elementToSelect= pkgFragment;
}
}
ISelection selection;
if (elementToSelect != null)
selection= new StructuredSelection(elementToSelect);
else
selection= StructuredSelection.EMPTY;
setSelection(selection, true);
}
}
|
33,130 |
Bug 33130 Type Selection Dialog maintains sizes
|
RC1 If you start Eclipse in the default (Tahoma 8) font and then change the Dialog font the next time the Type selection dialog is opened it will be cut off STEPS 1) Start Eclipse with default fonts 2) Open a Type Selection Dialog 3) Change the Dialog font 4) Open again - it will be sized based on the last selection
|
resolved fixed
|
1319109
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T16:17:52Z | 2003-02-25T21:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/OpenTypeSelectionDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import org.eclipse.swt.graphics.Point;
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.IDialogSettings;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* A dialog to select a type from a list of types. The selected type will be
* opened in the editor.
*/
public class OpenTypeSelectionDialog extends TypeSelectionDialog {
public static final int IN_HIERARCHY= IDialogConstants.CLIENT_ID + 1;
/** The dialog location. */
private Point fLocation;
/** The dialog size. */
private Point fSize;
/**
* Constructs an instance of <code>OpenTypeSelectionDialog</code>.
* @param parent the parent shell.
* @param context the context.
* @param elementKinds <code>IJavaSearchConstants.CLASS</code>, <code>IJavaSearchConstants.INTERFACE</code>
* or <code>IJavaSearchConstants.TYPE</code>
* @param scope the java search scope.
*/
public OpenTypeSelectionDialog(Shell parent, IRunnableContext context, int elementKinds, IJavaSearchScope scope) {
super(parent, context, elementKinds, scope);
}
/**
* @see Windows#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.OPEN_TYPE_DIALOG);
}
/*
* @see Window#close()
*/
public boolean close() {
writeSettings();
return super.close();
}
/**
* @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
Control control= super.createContents(parent);
readSettings();
return control;
}
/**
* Returns the dialog settings object used to share state
* between several find/replace dialogs.
*
* @return the dialog settings to be used
*/
private IDialogSettings getDialogSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
String sectionName= getClass().getName();
IDialogSettings subSettings= settings.getSection(sectionName);
if (subSettings == null)
subSettings= settings.addNewSection(sectionName);
return subSettings;
}
/**
* Initializes itself from the dialog settings with the same state
* as at the previous invocation.
*/
private void readSettings() {
IDialogSettings s= getDialogSettings();
try {
Shell shell= getShell();
int x= s.getInt("x"); //$NON-NLS-1$
int y= s.getInt("y"); //$NON-NLS-1$
shell.setLocation(x, y);
int width= s.getInt("width"); //$NON-NLS-1$
int height= s.getInt("height"); //$NON-NLS-1$
shell.setSize(width, height);
} catch (NumberFormatException e) {
fLocation= null;
fSize= null;
}
}
/**
* Stores it current configuration in the dialog store.
*/
private void writeSettings() {
IDialogSettings s= getDialogSettings();
Point location= getShell().getLocation();
s.put("x", location.x); //$NON-NLS-1$
s.put("y", location.y); //$NON-NLS-1$
Point size= getShell().getSize();
s.put("width", size.x); //$NON-NLS-1$
s.put("height", size.y); //$NON-NLS-1$
}
}
|
33,571 |
Bug 33571 SearchEngine.searchAllTypeNames: NPE when passing null as progress monitor
|
java.lang.NullPointerException at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob(JobManager.java:204) at org.eclipse.jdt.core.search.SearchEngine.searchAllTypeNames(SearchEngine.java:584) at org.eclipse.jdt.internal.corext.util.AllTypesCache.isIndexUpToDate(AllTypesCache.java:256) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.restoreState(TypeHierarchyViewPart.java:1349) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.createPartControl(TypeHierarchyViewPart.java:777) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:138) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.PartPane.createChildControl(PartPane.java:134) at org.eclipse.ui.internal.ViewPane.createChildControl(ViewPane.java:202) at org.eclipse.ui.internal.ViewFactory$2.run(ViewFactory.java:161) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.ViewFactory.busyRestoreView(ViewFactory.java:92) at org.eclipse.ui.internal.ViewFactory$1.run(ViewFactory.java:76) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.ViewFactory.restoreView(ViewFactory.java:72) at org.eclipse.ui.internal.ViewFactory$ViewReference.getPart(ViewFactory.java:326) at org.eclipse.ui.internal.WorkbenchPage$1.propertyChange(WorkbenchPage.java:121) at org.eclipse.ui.internal.LayoutPart.setVisible(LayoutPart.java:234) at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:345) at org.eclipse.ui.internal.PartTabFolder.setSelection(PartTabFolder.java:845) at org.eclipse.ui.internal.PartTabFolder.access$3(PartTabFolder.java:833) at org.eclipse.ui.internal.PartTabFolder$2.handleEvent(PartTabFolder.java:190) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:861) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:845) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:652) at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:1738) at org.eclipse.swt.custom.CTabFolder.onMouseDown(CTabFolder.java:1861) at org.eclipse.swt.custom.CTabFolder.access$4(CTabFolder.java:1853) at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:197) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1775) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1483) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1271) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1254) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
verified fixed
|
45a0f10
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:22:04Z | 2003-02-28T19:20:00Z |
org.eclipse.jdt.ui/core
| |
33,571 |
Bug 33571 SearchEngine.searchAllTypeNames: NPE when passing null as progress monitor
|
java.lang.NullPointerException at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob(JobManager.java:204) at org.eclipse.jdt.core.search.SearchEngine.searchAllTypeNames(SearchEngine.java:584) at org.eclipse.jdt.internal.corext.util.AllTypesCache.isIndexUpToDate(AllTypesCache.java:256) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.restoreState(TypeHierarchyViewPart.java:1349) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.createPartControl(TypeHierarchyViewPart.java:777) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:138) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.PartPane.createChildControl(PartPane.java:134) at org.eclipse.ui.internal.ViewPane.createChildControl(ViewPane.java:202) at org.eclipse.ui.internal.ViewFactory$2.run(ViewFactory.java:161) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.ViewFactory.busyRestoreView(ViewFactory.java:92) at org.eclipse.ui.internal.ViewFactory$1.run(ViewFactory.java:76) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.ViewFactory.restoreView(ViewFactory.java:72) at org.eclipse.ui.internal.ViewFactory$ViewReference.getPart(ViewFactory.java:326) at org.eclipse.ui.internal.WorkbenchPage$1.propertyChange(WorkbenchPage.java:121) at org.eclipse.ui.internal.LayoutPart.setVisible(LayoutPart.java:234) at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:345) at org.eclipse.ui.internal.PartTabFolder.setSelection(PartTabFolder.java:845) at org.eclipse.ui.internal.PartTabFolder.access$3(PartTabFolder.java:833) at org.eclipse.ui.internal.PartTabFolder$2.handleEvent(PartTabFolder.java:190) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:861) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:845) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:652) at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:1738) at org.eclipse.swt.custom.CTabFolder.onMouseDown(CTabFolder.java:1861) at org.eclipse.swt.custom.CTabFolder.access$4(CTabFolder.java:1853) at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:197) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1775) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1483) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1271) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1254) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
verified fixed
|
45a0f10
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:22:04Z | 2003-02-28T19:20:00Z |
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
| |
33,572 |
Bug 33572 Quick fix suggests to cast 'null' to 'int'
|
RC1 private void foo(int i, Object b) { foo(null, '1'); } Suggestion is cast null to int
|
resolved fixed
|
bdf9578
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:25:42Z | 2003-02-28T19:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.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.List;
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.dom.*;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
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.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.corext.textmanipulation.TextEdit;
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(ICorrectionContext context, List proposals) throws CoreException {
String[] args= context.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
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();
}
}
ASTRewriteCorrectionProposal castProposal= getCastProposal(context, castType, nodeToCast);
if (castProposal != null) {
proposals.add(castProposal);
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type type= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
type= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
type= decl.getType();
}
}
if (type != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
private static boolean canCast(String castTarget, ITypeBinding bindingToCast) {
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;
}
}
public static ASTRewriteCorrectionProposal getCastProposal(ICorrectionContext context, String castType, Expression nodeToCast) throws CoreException {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding != null && !canCast(castType, binding)) {
return null;
}
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image); //$NON-NLS-1$
String simpleCastType= proposal.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, ASTRewrite.TYPE));
} 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, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
return proposal;
}
public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
refactoring.setSaveChanges(false);
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);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName("e")); //$NON-NLS-1$
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static boolean canRemove(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(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= new NLSRefactoring(cu, JavaPreferencesSettings.getCodeGenerationSettings());
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, context.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().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
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();
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
if (accessBinding instanceof IMethodBinding) {
declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass();
}
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(declaringTypeBinding.getName()));
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, 2, image);
proposal.addImport(declaringTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(instanceTypeBinding.getName()));
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, 1, image);
proposal.addImport(instanceTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC);
}
public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
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.getMakeTypeStaticProposal(cu, typeDeclaration);
proposals.add(proposal);
}
}
public static void addUninitializedLocalVariableProposal(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
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= ASTResolving.getInitExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
fragment.setInitializer(expression);
rewrite.markAsInserted(expression);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.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);
}
}
public static void addConstructorFromSuperclassProposal(ICorrectionContext context, List proposals) {
ASTNode selectedNode= context.getCoveringNode();
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, 2));
}
}
}
public static void addUnusedMemberProposal(ICorrectionContext context, List proposals) throws CoreException {
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode);
if (declaration != null) {
ASTNode nodeToRemove= declaration;
if (declaration.getNodeType() == ASTNode.FIELD_DECLARATION) {
List fragments= ((FieldDeclaration) declaration).fragments();
if (fragments.size() > 1) {
for (int i= 0; i < fragments.size(); i++) {
VariableDeclarationFragment node= (VariableDeclarationFragment) fragments.get(i);
if (ASTNodes.isParent(selectedNode, node)) {
nodeToRemove= node;
break;
}
}
}
}
ASTRewrite rewrite= new ASTRewrite(nodeToRemove.getParent());
rewrite.markAsRemoved(nodeToRemove);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedmember.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
|
33,543 |
Bug 33543 Add catch clause to surrounding try doesn't honor code templates [quick fix]
|
RC1 Test Case import java.io.IOException; public class Test { public void foo() { try { ex1(); ex2(); } catch (IOException e) { e.printStackTrace(); } } public void ex1() throws IOException { } public void ex2 () throws InterruptedException { } } Observe: the generated catch block is empty.
|
resolved fixed
|
31f6c6d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:33:31Z | 2003-02-28T13:46:40Z |
org.eclipse.jdt.ui/core
| |
33,543 |
Bug 33543 Add catch clause to surrounding try doesn't honor code templates [quick fix]
|
RC1 Test Case import java.io.IOException; public class Test { public void foo() { try { ex1(); ex2(); } catch (IOException e) { e.printStackTrace(); } } public void ex1() throws IOException { } public void ex2 () throws InterruptedException { } } Observe: the generated catch block is empty.
|
resolved fixed
|
31f6c6d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:33:31Z | 2003-02-28T13:46:40Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
33,543 |
Bug 33543 Add catch clause to surrounding try doesn't honor code templates [quick fix]
|
RC1 Test Case import java.io.IOException; public class Test { public void foo() { try { ex1(); ex2(); } catch (IOException e) { e.printStackTrace(); } } public void ex1() throws IOException { } public void ex2 () throws InterruptedException { } } Observe: the generated catch block is empty.
|
resolved fixed
|
31f6c6d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:33:31Z | 2003-02-28T13:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.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.List;
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.dom.*;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
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.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.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateBuffer;
import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext;
import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.corext.util.Strings;
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(ICorrectionContext context, List proposals) throws CoreException {
String[] args= context.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
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();
}
}
ASTRewriteCorrectionProposal castProposal= getCastProposal(context, castType, nodeToCast);
if (castProposal != null) {
proposals.add(castProposal);
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type type= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
type= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
type= decl.getType();
}
}
if (type != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
private static boolean canCast(String castTarget, ITypeBinding bindingToCast) {
bindingToCast= ASTResolving.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;
}
}
public static ASTRewriteCorrectionProposal getCastProposal(ICorrectionContext context, String castType, Expression nodeToCast) throws CoreException {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding != null && !canCast(castType, binding)) {
return null;
}
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image); //$NON-NLS-1$
String simpleCastType= proposal.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, ASTRewrite.TYPE));
} 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, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
return proposal;
}
public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
refactoring.setSaveChanges(false);
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);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
ITypeBinding excBinding= uncaughtExceptions[i];
String varName= "e"; //$NON-NLS-1$
String imp= proposal.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);
if (catchBody != null) {
ASTNode node= rewrite.createPlaceholder(catchBody, ASTRewrite.STATEMENT);
newClause.getBody().statements().add(node);
}
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static boolean canRemove(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(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= new NLSRefactoring(cu, JavaPreferencesSettings.getCodeGenerationSettings());
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, context.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().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
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();
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
if (accessBinding instanceof IMethodBinding) {
declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass();
}
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(declaringTypeBinding.getName()));
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, 2, image);
proposal.addImport(declaringTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(instanceTypeBinding.getName()));
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, 1, image);
proposal.addImport(instanceTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC);
}
public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
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.getMakeTypeStaticProposal(cu, typeDeclaration);
proposals.add(proposal);
}
}
public static void addUninitializedLocalVariableProposal(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
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= ASTResolving.getInitExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
fragment.setInitializer(expression);
rewrite.markAsInserted(expression);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.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);
}
}
public static void addConstructorFromSuperclassProposal(ICorrectionContext context, List proposals) {
ASTNode selectedNode= context.getCoveringNode();
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, 2));
}
}
}
public static void addUnusedMemberProposal(ICorrectionContext context, List proposals) throws CoreException {
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode);
if (declaration != null) {
ASTNode nodeToRemove= declaration;
if (declaration.getNodeType() == ASTNode.FIELD_DECLARATION) {
List fragments= ((FieldDeclaration) declaration).fragments();
if (fragments.size() > 1) {
for (int i= 0; i < fragments.size(); i++) {
VariableDeclarationFragment node= (VariableDeclarationFragment) fragments.get(i);
if (ASTNodes.isParent(selectedNode, node)) {
nodeToRemove= node;
break;
}
}
}
}
ASTRewrite rewrite= new ASTRewrite(nodeToRemove.getParent());
rewrite.markAsRemoved(nodeToRemove);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedmember.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
|
32,913 |
Bug 32913 No swapped arguments QF for overloaded methods
|
RC1: - given a method foo(int, String) the call to foo("abc", 123) results in a "Swap Arguments" QF - add a method declaration foo() Observe: the call to foo("abc", 123) no longer results in a "Swap Arguments" QF
|
resolved fixed
|
7fae6fb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:37:01Z | 2003-02-25T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.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.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
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.dom.*;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class UnresolvedElementsSubProcessor {
public static void getVariableProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
// type that defines the variable, null if local
ITypeBinding binding= null;
ITypeBinding declaringTypeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (declaringTypeBinding == null) {
return;
}
// possible kind of the node
int similarNodeKind= SimilarElementsRequestor.VARIABLES;
Name node= null;
if (selectedNode instanceof SimpleName) {
node= (SimpleName) selectedNode;
ASTNode parent= node.getParent();
if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) {
similarNodeKind |= SimilarElementsRequestor.CLASSES;
}
} else if (selectedNode instanceof QualifiedName) {
QualifiedName qualifierName= (QualifiedName) selectedNode;
ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding();
if (qualifierBinding != null) {
node= qualifierName.getName();
binding= qualifierBinding;
} else {
node= qualifierName.getQualifier();
if (node.isSimpleName()) {
similarNodeKind |= SimilarElementsRequestor.REF_TYPES;
} else {
similarNodeKind= SimilarElementsRequestor.REF_TYPES;
}
}
} else if (selectedNode instanceof FieldAccess) {
FieldAccess access= (FieldAccess) selectedNode;
Expression expression= access.getExpression();
if (expression != null) {
binding= expression.resolveTypeBinding();
if (binding != null) {
node= access.getName();
}
}
} else if (selectedNode instanceof SuperFieldAccess) {
binding= declaringTypeBinding.getSuperclass();
} else if (selectedNode instanceof SimpleType) {
similarNodeKind= SimilarElementsRequestor.REF_TYPES;
node= ((SimpleType) selectedNode).getName();
}
if (node == null) {
return;
}
// avoid corrections like int i= i;
String assignedName= null;
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier();
}
// corrections
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, similarNodeKind);
for (int i= 0; i < elements.length; i++) {
SimilarElement curr= elements[i];
if ((curr.getKind() & SimilarElementsRequestor.VARIABLES) != 0 && !curr.getName().equals(assignedName)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", curr.getName()); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), curr.getName(), 3));
}
}
// add type proposals
if ((similarNodeKind & SimilarElementsRequestor.ALL_TYPES) != 0) {
int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(elements, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if ((similarNodeKind & SimilarElementsRequestor.VARIABLES) == 0) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) {
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image));
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
senderBinding= ASTResolving.getBindingOfParentType(anonymDecl.getParent());
if (!senderBinding.isAnonymous()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image));
}
}
}
}
if (binding == null) {
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
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, 1, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
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, 3, image));
}
}
}
public static void getTypeProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
int kind= SimilarElementsRequestor.ALL_TYPES;
ASTNode parent= selectedNode.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.REF_TYPES | SimilarElementsRequestor.VOIDTYPE;
}
break;
case ASTNode.INSTANCEOF_EXPRESSION:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.THROW_STATEMENT:
case ASTNode.CLASS_INSTANCE_CREATION:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
int superParent= parent.getParent().getNodeType();
if (superParent == ASTNode.CATCH_CLAUSE) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
default:
}
Name node= null;
if (selectedNode instanceof SimpleType) {
node= ((SimpleType) selectedNode).getName();
} else if (selectedNode instanceof ArrayType) {
Type elementType= ((ArrayType) selectedNode).getElementType();
if (elementType.isSimpleType()) {
node= ((SimpleType) elementType).getName();
}
} else if (selectedNode instanceof Name) {
node= (Name) selectedNode;
} else {
return;
}
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);
addSimilarTypeProposals(elements, cu, node, 3, proposals);
// add type
addNewTypeProposals(cu, node, kind, 0, proposals);
}
private static void addSimilarTypeProposals(SimilarElement[] elements, ICompilationUnit cu, Name node, int relevance, List proposals) throws JavaModelException {
// 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= Bindings.getFullyQualifiedName(binding);
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 JavaModelException {
CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String simpleName= importEdit.addImport(fullName);
TextEdit root= proposal.getRootTextEdit();
if (!importEdit.isEmpty()) {
root.add(importEdit); //$NON-NLS-1$
}
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", fullName)); //$NON-NLS-1$
proposal.setRelevance(relevance + 20);
} else {
root.add(SimpleTextEdit.createReplace(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", simpleName)); //$NON-NLS-1$
proposal.setRelevance(relevance);
}
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, List 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(ICorrectionContext context, boolean needsNewName, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
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();
// corrections
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, nameNode, SimilarElementsRequestor.METHODS);
ArrayList parameterMismatchs= new ArrayList();
for (int i= 0; i < elements.length; i++) {
String curr= elements[i].getName();
if (curr.equals(methodName) && needsNewName) {
parameterMismatchs.add(elements[i]);
continue;
}
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, context.getCompilationUnit(), context.getOffset(), context.getLength(), curr, 2));
}
if (parameterMismatchs.size() == 1) {
addParameterMissmatchProposals(context, (SimilarElement) parameterMismatchs.get(0), arguments, proposals);
}
// new method
ITypeBinding binding= null;
if (sender != null) {
binding= sender.resolveTypeBinding();
} else {
binding= ASTResolving.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;
if (cu.equals(targetCU)) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", methodName); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { methodName, targetCU.getElementName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
}
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 1, image));
if (binding.isAnonymous() && cu.equals(targetCU)) {
ASTNode anonymDecl= astRoot.findDeclaringNode(binding);
if (anonymDecl != null) {
binding= ASTResolving.getBindingOfParentType(anonymDecl.getParent());
if (!binding.isAnonymous()) {
String[] args= new String[] { methodName, 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, 1, image));
}
}
}
}
}
}
private static void addParameterMissmatchProposals(ICorrectionContext context, SimilarElement elem, List arguments, List proposals) throws CoreException {
String[] paramTypes= elem.getParameterTypes();
ITypeBinding[] argTypes= getArgumentTypes(arguments);
if (paramTypes == null || argTypes == null) {
return;
}
if (paramTypes.length == argTypes.length) {
int[] indexOfDiff= new int[paramTypes.length];
int nDiffs= 0;
for (int i= 0; i < argTypes.length; i++) {
if (!ASTResolving.canAssign(argTypes[i], paramTypes[i])) {
indexOfDiff[nDiffs++]= i;
}
}
for (int k= 0; k < nDiffs; k++) {
int idx= indexOfDiff[k];
Expression nodeToCast= (Expression) arguments.get(idx);
String castType= paramTypes[idx];
if (nodeToCast.getNodeType() != ASTNode.CAST_EXPRESSION) {
ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.getCastProposal(context, castType, nodeToCast);
if (proposal != null) {
proposals.add(proposal);
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparametercast.description", castType)); //$NON-NLS-1$
}
}
}
if (nDiffs == 2) { // try to swap
int idx1= indexOfDiff[0];
int idx2= indexOfDiff[1];
if (ASTResolving.canAssign(argTypes[idx1], paramTypes[idx2]) && ASTResolving.canAssign(argTypes[idx2], paramTypes[idx1])) {
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 label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.swapparameters.description"); //$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);
}
}
}
}
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= ASTResolving.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
res[i]= curr;
}
return res;
}
public static void getConstructorProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ITypeBinding targetBinding= null;
List arguments= 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= ASTResolving.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding.getSuperclass();
arguments= ((SuperConstructorInvocation) selectedNode).arguments();
}
} else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding;
arguments= ((ConstructorInvocation) selectedNode).arguments();
}
}
if (targetBinding != null && targetBinding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding);
if (targetCU != null) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", targetBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 1, image));
}
}
}
public static void getAmbiguosTypeReferenceProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
int offset= context.getOffset();
int len= context.getLength();
IJavaElement[] elements= cu.codeSelect(offset, len);
for (int i= 0; i < elements.length; i++) {
IJavaElement curr= elements[i];
if (curr instanceof IType) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 1, image);
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
importEdit.addImport(qualifiedTypeName);
importEdit.setFindAmbiguosImports(true);
proposal.getRootTextEdit().add(importEdit);
proposals.add(proposal);
}
}
}
}
|
33,535 |
Bug 33535 Quickfix causes exceptions
|
- Unzip to a Java project(default package) (I'll attach the source). - Go to file w/error - Click on icon in left margin to get quickfix options - Exceptions are produce !SESSION feb 28, 2003 14:31:43.732 --------------------------------------------- java.version=1.4.1_01 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=no_NO Command-line arguments: -os win32 -ws win32 -arch x86 -install file:C:/eclipse/ !ENTRY org.eclipse.ui 4 4 feb 28, 2003 14:31:43.732 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 feb 28, 2003 14:31:43.752 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.ModifierCorrectionSubProcessor.getNe ededVisibility(ModifierCorrectionSubProcessor.java:143) at org.eclipse.jdt.internal.ui.text.correction.ModifierCorrectionSubProcessor.addNo nAccessibleMemberProposal(ModifierCorrectionSubProcessor.java:86) at org.eclipse.jdt.internal.ui.text.correction.QuickFixProcessor.process (QuickFixProcessor.java:190) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor.collectCorre ctions(JavaCorrectionProcessor.java:205) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor.processProbl emAnnotations(JavaCorrectionProcessor.java:173) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor.computeCompl etionProposals(JavaCorrectionProcessor.java:136) at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals (ContentAssistant.java:1281) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals (CompletionProposalPopup.java:178) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$7 (CompletionProposalPopup.java:177) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$3.run (CompletionProposalPopup.java:139) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.showProposals (CompletionProposalPopup.java:134) at org.eclipse.jface.text.contentassist.ContentAssistant.showPossibleCompletions (ContentAssistant.java:1201) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant.showPossible Completions(JavaCorrectionAssistant.java:153) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer .doOperation(CompilationUnitEditor.java:153) at org.eclipse.jdt.internal.ui.javaeditor.JavaSelectMarkerRulerAction.run (JavaSelectMarkerRulerAction.java:52) at org.eclipse.ui.texteditor.AbstractRulerActionDelegate.run (AbstractRulerActionDelegate.java:98) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:250) at org.eclipse.ui.internal.PluginAction.run(PluginAction.java:212) at org.eclipse.ui.texteditor.AbstractTextEditor$4.triggerAction (AbstractTextEditor.java:1674) at org.eclipse.ui.texteditor.AbstractTextEditor$4.mouseUp (AbstractTextEditor.java:1681) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:130) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1775) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1483) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1271) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1254) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
057b809
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T19:59:53Z | 2003-02-28T13:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java
|
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
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 void addNonAccessibleMemberProposal(ICorrectionContext context, List proposals, int kind) throws JavaModelException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
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;
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();
} else if (binding instanceof ITypeBinding) {
typeBinding= (ITypeBinding) binding;
name= binding.getName();
} else {
return;
}
if (typeBinding != null && typeBinding.isFromSource()) {
int includedModifiers= 0;
int excludedModifiers= 0;
String label;
if (kind == 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$
} else if (kind == TO_STATIC) {
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertostatic.description", name); //$NON-NLS-1$
includedModifiers= Modifier.STATIC;
} else if (kind == TO_NON_STATIC) {
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertononstatic.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.STATIC;
} else if (kind == TO_NON_PRIVATE) {
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertoprotected.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.PRIVATE;
includedModifiers= Modifier.PROTECTED;
} else {
return;
}
ICompilationUnit targetCU= 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, 0, image));
}
}
}
public static void addNonFinalLocalProposal(ICorrectionContext context, List proposals) {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
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, 0, 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= ASTResolving.getBindingOfParentType(currNode);
if (currNodeBinding == null) { // import
return Modifier.PUBLIC;
}
ITypeBinding curr= currNodeBinding;
while (curr != null) {
if (curr.getKey().equals(targetType.getKey())) {
return Modifier.PROTECTED;
}
curr= curr.getSuperclass();
}
if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
return 0;
}
return Modifier.PUBLIC;
}
public static void addAbstractMethodProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
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 (context.getProblemId() == IProblem.AbstractMethodInAbstractClass || parentIsAbstractClass) {
ASTRewrite rewrite= new ASTRewrite(decl.getParent());
AST ast= astRoot.getAST();
MethodDeclaration modifiedNode= ast.newMethodDeclaration();
modifiedNode.setConstructor(decl.isConstructor());
modifiedNode.setExtraDimensions(decl.getExtraDimensions());
modifiedNode.setModifiers(decl.getModifiers() & ~Modifier.ABSTRACT);
rewrite.markAsModified(decl, modifiedNode);
if (hasNoBody) {
Block newBody= ast.newBlock();
rewrite.markAsInserted(newBody);
decl.setBody(newBody);
Expression expr= ASTResolving.getInitExpression(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, 1, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (!hasNoBody && context.getProblemId() == IProblem.BodyForAbstractMethod) {
ASTRewrite rewrite= new ASTRewrite(decl.getParent());
rewrite.markAsRemoved(decl.getBody());
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, 0, image);
proposal2.ensureNoModifications();
proposals.add(proposal2);
}
if (context.getProblemId() == IProblem.AbstractMethodInAbstractClass && (parentTypeDecl != null)) {
ASTRewriteCorrectionProposal proposal= getMakeTypeStaticProposal(cu, parentTypeDecl);
proposals.add(proposal);
}
}
public static void addNativeMethodProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
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();
MethodDeclaration modifiedNode= ast.newMethodDeclaration();
modifiedNode.setConstructor(decl.isConstructor());
modifiedNode.setExtraDimensions(decl.getExtraDimensions());
modifiedNode.setModifiers(decl.getModifiers() & ~Modifier.NATIVE);
rewrite.markAsModified(decl, modifiedNode);
Block newBody= ast.newBlock();
rewrite.markAsInserted(newBody);
decl.setBody(newBody);
Expression expr= ASTResolving.getInitExpression(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, 1, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl.getBody() != null) {
ASTRewrite rewrite= new ASTRewrite(decl.getParent());
rewrite.markAsRemoved(decl.getBody());
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, 0, image);
proposal2.ensureNoModifications();
proposals.add(proposal2);
}
}
public static ASTRewriteCorrectionProposal getMakeTypeStaticProposal(ICompilationUnit cu, TypeDeclaration typeDeclaration) throws CoreException {
ASTRewrite rewrite= new ASTRewrite(typeDeclaration.getParent());
AST ast= typeDeclaration.getAST();
TypeDeclaration modifiedNode= ast.newTypeDeclaration();
modifiedNode.setInterface(typeDeclaration.isInterface());
modifiedNode.setModifiers(typeDeclaration.getModifiers() | Modifier.ABSTRACT);
rewrite.markAsModified(typeDeclaration, modifiedNode);
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, 3, image);
proposal.ensureNoModifications();
return proposal;
}
public static void addMethodRequiresBodyProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
AST ast= context.getASTRoot().getAST();
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof MethodDeclaration)) {
return;
}
MethodDeclaration decl= (MethodDeclaration) selectedNode;
ASTRewrite rewrite= new ASTRewrite(decl);
MethodDeclaration modifiedNode= ast.newMethodDeclaration();
modifiedNode.setConstructor(decl.isConstructor());
modifiedNode.setExtraDimensions(decl.getExtraDimensions());
modifiedNode.setModifiers(decl.getModifiers() & ~Modifier.ABSTRACT);
rewrite.markAsModified(decl, modifiedNode);
Block body= ast.newBlock();
decl.setBody(body);
rewrite.markAsInserted(body);
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, 3, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
public static void addNeedToEmulateProposal(ICorrectionContext context, List proposals) {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
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, 0, image));
}
}
}
|
33,521 |
Bug 33521 Cannot turn javadoc generation off
|
Eclipse 2.1 RC1 Apologies if I'm missing something, but since moving from M3 to RC1, the options under Prefs->Java->CodeGeneration no longer include a way of stopping Eclipse from adding javadoc comments on creation of new types. The help system still reflects the M3-style help dialogs which _did_ have these options. I could just edit the javadoc templates, but I'd rather not. I want to just turn them off altogether. Have these options been removed, or have they just been moved to a different location?
|
resolved fixed
|
fbaf8a3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T20:34:33Z | 2003-02-28T08:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeTemplateBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateSet;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
*/
public class CodeTemplateBlock {
private class CodeTemplateAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] NO_CHILDREN= new Object[0];
private CodeTemplates fTemplates;
public CodeTemplateAdapter(CodeTemplates templates) {
fTemplates= templates;
}
public void customButtonPressed(TreeListDialogField field, int index) {
doButtonPressed(index, field.getSelectedElements());
}
public void selectionChanged(TreeListDialogField field) {
List selected= field.getSelectedElements();
field.enableButton(IDX_EDIT, canEdit(selected));
field.enableButton(IDX_EXPORT, !selected.isEmpty());
updateSourceViewerInput(selected);
}
public void doubleClicked(TreeListDialogField field) {
List selected= field.getSelectedElements();
if (canEdit(selected)) {
doButtonPressed(IDX_EDIT, selected);
}
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element == COMMENT_NODE || element == CODE_NODE) {
return getTemplateOfCategory(element == COMMENT_NODE);
}
return NO_CHILDREN;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof Template) {
Template template= (Template) element;
if (template.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) {
return COMMENT_NODE;
}
return CODE_NODE;
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element == COMMENT_NODE || element == CODE_NODE);
}
public void dialogFieldChanged(DialogField field) {
}
public void keyPressed(TreeListDialogField field, KeyEvent event) {
}
}
private static class CodeTemplateLabelProvider extends LabelProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
/* if (element == COMMENT_NODE) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG);
}
if (element == CODE_NODE) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPCONT);
}
Template template = (Template) element;
String name= template.getName();
if (CodeTemplates.CATCHBLOCK.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
} else if (CodeTemplates.METHODSTUB.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_MISC_DEFAULT);
} else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE));
} else if (CodeTemplates.NEWTYPE.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CUNIT);
} else if (CodeTemplates.TYPECOMMENT.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS);
} else if (CodeTemplates.METHODCOMMENT.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
} else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PROTECTED, JavaElementImageDescriptor.OVERRIDES, JavaElementImageProvider.SMALL_SIZE));
} else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE));
}*/
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
if (element == COMMENT_NODE || element == CODE_NODE) {
return (String) element;
}
Template template = (Template) element;
String name= template.getName();
if (CodeTemplates.CATCHBLOCK.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$
} else if (CodeTemplates.METHODSTUB.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$
} else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$
} else if (CodeTemplates.NEWTYPE.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$
} else if (CodeTemplates.TYPECOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.METHODCOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$
}
return template.getDescription();
}
}
private final static int IDX_EDIT= 0;
private final static int IDX_IMPORT= 2;
private final static int IDX_EXPORT= 3;
private final static int IDX_EXPORTALL= 4;
protected final static Object COMMENT_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$
protected final static Object CODE_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$
private static final String PREF_JAVADOC_STUBS= PreferenceConstants.CODEGEN_ADD_COMMENTS;
private TreeListDialogField fCodeTemplateTree;
private SelectionButtonDialogField fCreateJavaDocComments;
protected CodeTemplates fTemplates;
private PixelConverter fPixelConverter;
private SourceViewer fPatternViewer;
private Control fSWTWidget;
public CodeTemplateBlock() {
fTemplates= CodeTemplates.getInstance();
CodeTemplateAdapter adapter= new CodeTemplateAdapter(fTemplates);
String[] buttonLabels= new String[] {
/* IDX_EDIT*/ PreferencesMessages.getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$
/* */ null,
/* IDX_IMPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$
/* IDX_EXPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$
/* IDX_EXPORTALL */ PreferencesMessages.getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$
};
fCodeTemplateTree= new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider());
fCodeTemplateTree.setDialogFieldListener(adapter);
fCodeTemplateTree.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$
fCodeTemplateTree.enableButton(IDX_EXPORT, false);
fCodeTemplateTree.enableButton(IDX_EDIT, false);
fCodeTemplateTree.addElement(COMMENT_NODE);
fCodeTemplateTree.addElement(CODE_NODE);
fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateJavaDocComments.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$
fCreateJavaDocComments.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS));
fCodeTemplateTree.selectFirstElement();
}
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
fSWTWidget= parent;
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
//layout.marginHeight= 0;
//layout.marginWidth= 0;
layout.numColumns= 2;
composite.setLayout(layout);
fCreateJavaDocComments.doFillIntoGrid(composite, 2);
fCodeTemplateTree.doFillIntoGrid(composite, 3);
LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2);
LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null));
fPatternViewer= createViewer(composite, 2);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private SourceViewer createViewer(Composite parent, int nColumns) {
Label label= new Label(parent, SWT.NONE);
label.setText(PreferencesMessages.getString("CodeTemplateBlock.preview")); //$NON-NLS-1$
GridData data= new GridData();
data.horizontalSpan= nColumns;
label.setLayoutData(data);
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
IDocument document= new Document();
IDocumentPartitioner partitioner= tools.createDocumentPartitioner();
document.setDocumentPartitioner(partitioner);
partitioner.connect(document);
viewer.configure(new JavaSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(document);
viewer.getTextWidget().setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.horizontalSpan= nColumns;
data.heightHint= fPixelConverter.convertHeightInCharsToPixels(5);
control.setLayoutData(data);
return viewer;
}
protected Template[] getTemplateOfCategory(boolean isComment) {
ArrayList res= new ArrayList();
Template[] templates= fTemplates.getTemplates();
for (int i= 0; i < templates.length; i++) {
Template curr= templates[i];
if (isComment == curr.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) {
res.add(curr);
}
}
return (Template[]) res.toArray(new Template[res.size()]);
}
protected static boolean canEdit(List selected) {
return selected.size() == 1 && (selected.get(0) instanceof Template);
}
protected void updateSourceViewerInput(List selection) {
if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) {
return;
}
if (selection.size() == 1 && selection.get(0) instanceof Template) {
Template template= (Template) selection.get(0);
fPatternViewer.getDocument().set(template.getPattern());
} else {
fPatternViewer.getDocument().set(""); //$NON-NLS-1$
}
}
protected void doButtonPressed(int buttonIndex, List selected) {
if (buttonIndex == IDX_EDIT) {
edit((Template) selected.get(0));
} else if (buttonIndex == IDX_EXPORT) {
export(selected);
} else if (buttonIndex == IDX_EXPORTALL) {
exportAll();
} else if (buttonIndex == IDX_IMPORT) {
import_();
}
}
private void edit(Template template) {
Template newTemplate= new Template(template);
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, false, new String[0]);
if (dialog.open() == EditTemplateDialog.OK) {
// changed
template.setDescription(newTemplate.getDescription());
template.setPattern(newTemplate.getPattern());
fCodeTemplateTree.refresh(template);
fCodeTemplateTree.selectElements(new StructuredSelection(template));
}
}
private void import_() {
FileDialog dialog= new FileDialog(getShell());
dialog.setText(PreferencesMessages.getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.import.extension")}); //$NON-NLS-1$
String path= dialog.open();
if (path != null) {
try {
fTemplates.addFromFile(new File(path), false);
} catch (CoreException e) {
openReadErrorDialog(e);
}
fCodeTemplateTree.refresh();
}
}
private void exportAll() {
export(fTemplates);
}
private void export(List selected) {
TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag());
for (int i= 0; i < selected.size(); i++) {
Object curr= selected.get(i);
if (curr instanceof Template) {
addToTemplateSet(templateSet, (Template) curr);
} else {
Template[] templates= getTemplateOfCategory(curr == COMMENT_NODE);
for (int k= 0; k < templates.length; k++) {
addToTemplateSet(templateSet, templates[k]);
}
}
}
export(templateSet);
}
private void addToTemplateSet(TemplateSet set, Template template) {
if (set.getFirstTemplate(template.getName()) == null) {
set.add(template);
}
}
private void export(TemplateSet templateSet) {
FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(PreferencesMessages.getFormattedString("CodeTemplateBlock.export.title", String.valueOf(templateSet.getTemplates().length))); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.export.extension")}); //$NON-NLS-1$
dialog.setFileName(PreferencesMessages.getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
File file= new File(path);
if (file.isHidden()) {
String title= PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$
String message= PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
return;
}
if (file.exists() && !file.canWrite()) {
String title= PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$
String message= PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
return;
}
if (!file.exists() || confirmOverwrite(file)) {
try {
templateSet.saveToFile(file);
} catch (CoreException e) {
if (e.getStatus().getException() instanceof FileNotFoundException) {
String title= PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$
String message= PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.fileNotFound", e.getStatus().getException().getLocalizedMessage()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
return;
}
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
}
}
private boolean confirmOverwrite(File file) {
return MessageDialog.openQuestion(getShell(),
PreferencesMessages.getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$
PreferencesMessages.getFormattedString("CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$
}
public void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS));
try {
fTemplates.restoreDefaults();
} catch (CoreException e) {
JavaPlugin.log(e);
openReadErrorDialog(e);
}
// refresh
fCodeTemplateTree.refresh();
}
public boolean performOk(boolean enabled) {
IPreferenceStore prefs= PreferenceConstants.getPreferenceStore();
prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected());
JavaPlugin.getDefault().savePluginPreferences();
try {
fTemplates.save();
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
return true;
}
public void performCancel() {
try {
fTemplates.reset();
} catch (CoreException e) {
openReadErrorDialog(e);
}
}
private void openReadErrorDialog(CoreException e) {
String title= PreferencesMessages.getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$
// Show parse error in a user dialog without logging
if (e.getStatus().getCode() == IJavaStatusConstants.TEMPLATE_PARSE_EXCEPTION) {
String message= e.getStatus().getException().getLocalizedMessage();
if (message != null)
message= PreferencesMessages.getFormattedString("CodeTemplateBlock.error.parse.message", message); //$NON-NLS-1$
else
message= PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
} else {
String message= PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
private void openWriteErrorDialog(CoreException e) {
String title= PreferencesMessages.getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
|
33,373 |
Bug 33373 Internal error generating javadoc for simple project
|
Build: 2.1 RC1 1) Create a simple project 2) Switch to java perspective 3) Select the project, and choose Project > Generate Javadoc -> Error appears in the log file: !MESSAGE Internal Error !STACK 1 Java Model Exception: Java Model Status [Bpp does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException(JavaElement.java:482) at org.eclipse.jdt.internal.core.JavaModelManager.getPerProjectInfoCheckExistence(JavaModelManager.java:956) at org.eclipse.jdt.internal.core.JavaProject.getResolvedClasspath(JavaProject.java:1460) at org.eclipse.jdt.internal.core.JavaProject.getResolvedClasspath(JavaProject.java:1445) at org.eclipse.jdt.internal.core.JavaProject.generateInfos(JavaProject.java:974) at org.eclipse.jdt.internal.core.Openable.buildStructure(Openable.java:71) at org.eclipse.jdt.internal.core.Openable.openWhenClosed(Openable.java:394) at org.eclipse.jdt.internal.core.JavaProject.openWhenClosed(JavaProject.java:1866) at org.eclipse.jdt.internal.core.JavaElement.openHierarchy(JavaElement.java:503) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:296) at org.eclipse.jdt.internal.core.JavaElement.getChildren(JavaElement.java:252) at org.eclipse.jdt.internal.core.JavaProject.getPackageFragmentRoots(JavaProject.java:1296) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.getValidProject(JavadocOptionsManager.java:1129) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.getSelectableJavaElement(JavadocOptionsManager.java:1120) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.getProjects(JavadocOptionsManager.java:1050) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.getValidSelection(JavadocOptionsManager.java:1041) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.loadDefaults(JavadocOptionsManager.java:346) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.loadStore(JavadocOptionsManager.java:256) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.<init>(JavadocOptionsManager.java:186) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.init(JavadocWizard.java:421) at org.eclipse.jdt.internal.ui.actions.GenerateJavadocAction.run(GenerateJavadocAction.java:45) at org.eclipse.ui.internal.PluginAction.runWithEvent(PluginAction.java:250) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:202) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:456) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:403) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:397) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1254) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
verified fixed
|
d6809a7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T21:57:12Z | 2003-02-26T22:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocOptionsManager.java
|
/*
* Copyright (c) 2002 IBM Corp. All rights reserved.
* This file is 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
*/
package org.eclipse.jdt.internal.ui.javadocexport;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
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.Path;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
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.launching.ExecutionArguments;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage;
public class JavadocOptionsManager {
private IWorkspaceRoot fRoot;
//consider making a List
private List fProjects;
private IFile fXmlfile;
private StatusInfo fWizardStatus;
private List fSourceElements;
private List fSelectedElements;
private String fAccess;
private String fDocletpath;
private String fDocletname;
private boolean fFromStandard;
private String fStylesheet;
private String fAdditionalParams;
private String fOverview;
private String fTitle;
private String fJDocCommand;
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;
//list of hrefs in string format
private Map fLinks;
//add-on for multi-project version
private String fDestination;
private String fDependencies;
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 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$
private final String FROMSTANDARD= "fromStandard"; //$NON-NLS-1$
private final String ANTPATH= "antpath"; //$NON-NLS-1$
public final String SOURCE= "source"; //$NON-NLS-1$
/**
* @param xmlJavadocFile The ant file to take initl values from or null, if not started from an ant file.
* @param setting Dialog settings for the Javadoc exporter.
*/
public JavadocOptionsManager(IFile xmlJavadocFile, IDialogSettings settings, ISelection currSelection) {
Element element;
this.fRoot= ResourcesPlugin.getWorkspace().getRoot();
fJDocCommand= JavadocPreferencePage.getJavaDocCommand();
this.fXmlfile= xmlJavadocFile;
this.fWizardStatus= new StatusInfo();
this.fLinks= new HashMap();
fProjects= new ArrayList();
if (xmlJavadocFile != null) {
try {
JavadocReader reader= new JavadocReader(xmlJavadocFile.getContents());
element= reader.readXML();
IJavaProject p= reader.getProject();
if (element == null || p == null) {
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
} else {
fProjects.add(p);
loadStore(element, settings);
}
} catch (CoreException e) {
JavaPlugin.log(e);
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
} catch (IOException e) {
JavaPlugin.log(e);
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectIOE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
} catch (SAXException e) {
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectSAXE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
}
} else
loadStore(settings, currSelection);
}
private void loadStore(IDialogSettings settings, ISelection sel) {
if (settings != null) {
//getValidSelection will also find the project
fSelectedElements= getValidSelection(sel);
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$
}
//load a default antpath
fAntpath= settings.get(ANTPATH);
if (fAntpath == null)
fAntpath= ""; //$NON-NLS-1$
//$NON-NLS-1$
//load a default antpath
fDestination= settings.get(DESTINATION);
if (fDestination == null)
fDestination= ""; //$NON-NLS-1$
//$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$
fAdditionalParams= settings.get(EXTRAOPTIONS);
if (fAdditionalParams == null)
fAdditionalParams= ""; //$NON-NLS-1$
fOverview= settings.get(OVERVIEW);
if (fOverview == null)
fOverview= ""; //$NON-NLS-1$
fUse= loadbutton(settings.get(USE));
fAuthor= loadbutton(settings.get(AUTHOR));
fVersion= loadbutton(settings.get(VERSION));
fNodeprecated= loadbutton(settings.get(NODEPRECATED));
fNoDeprecatedlist= loadbutton(settings.get(NODEPRECATEDLIST));
fNonavbar= loadbutton(settings.get(NONAVBAR));
fNoindex= loadbutton(settings.get(NOINDEX));
fNotree= loadbutton(settings.get(NOTREE));
fSplitindex= loadbutton(settings.get(SPLITINDEX));
fOpenInBrowser= loadbutton(settings.get(OPENINBROWSER));
fJDK14Mode= loadbutton(settings.get(SOURCE));
//get the set of project specific data
loadLinksFromDialogSettings(settings);
} else
loadDefaults(sel);
}
private String getDefaultAntPath(IJavaProject project) {
if (project != null) {
IPath path= project.getProject().getLocation();
if (path != null)
return path.append("javadoc.xml").toOSString(); //$NON-NLS-1$
}
return ""; //$NON-NLS-1$
}
private String getDefaultDestination(IJavaProject project) {
if (project != null) {
URL url= JavaUI.getProjectJavadocLocation(project);
//uses default if source is has http protocol
if (url == null || !url.getProtocol().equals("file")) { //$NON-NLS-1$
IPath path= project.getProject().getLocation();
if (path != null)
return path.append("doc").toOSString(); //$NON-NLS-1$
} else {
//must do this to remove leading "/"
return (new File(url.getFile())).getPath();
}
}
return ""; //$NON-NLS-1$
}
/**
* Method creates a list of data structes that contain
* The destination, antfile location and the list of library/project references for every
* project in the workspace.Defaults are created for new project.
*/
private void loadLinksFromDialogSettings(IDialogSettings settings) {
//sets data for projects if stored in the dialog settings
if (settings != null) {
IDialogSettings links= settings.getSection("projects"); //$NON-NLS-1$
if (links != null) {
IDialogSettings[] projs= links.getSections();
for (int i= 0; i < projs.length; i++) {
IDialogSettings iDialogSettings= projs[i];
String projectName= iDialogSettings.getName();
IProject project= fRoot.getProject(projectName);
//make sure project has not been removed
if (project.exists()) {
IJavaProject javaProject= JavaCore.create(project);
if (!fLinks.containsKey(javaProject)) {
String hrefs= iDialogSettings.get(HREF);
if (hrefs == null) {
hrefs= ""; //$NON-NLS-1$
}
String destdir= iDialogSettings.get(DESTINATION);
if (destdir == null || destdir.length() == 0) {
destdir= getDefaultDestination(javaProject);
}
String antpath= iDialogSettings.get(ANTPATH);
if (antpath == null || antpath.length() == 0) {
antpath= getDefaultAntPath(javaProject);
}
ProjectData data= new ProjectData(javaProject);
data.setDestination(destdir);
data.setAntpath(antpath);
data.setlinks(hrefs);
if (!fLinks.containsValue(javaProject))
fLinks.put(javaProject, data);
}
}
}
}
}
//finds projects in the workspace that have been added since the
//last time the wizard was run
IProject[] projects= fRoot.getProjects();
for (int i= 0; i < projects.length; i++) {
IProject iProject= projects[i];
IJavaProject javaProject= JavaCore.create(iProject);
if (!fLinks.containsKey(javaProject)) {
ProjectData data= new ProjectData(javaProject);
data.setDestination(getDefaultDestination(javaProject));
data.setAntpath(getDefaultAntPath(javaProject));
data.setlinks(""); //$NON-NLS-1$
fLinks.put(javaProject, data);
}
}
}
//loads defaults for wizard (nothing is stored)
private void loadDefaults(ISelection sel) {
fSelectedElements= getValidSelection(sel);
fAccess= PUBLIC;
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
fTitle= ""; //$NON-NLS-1$
fStylesheet= ""; //$NON-NLS-1$
fAdditionalParams= ""; //$NON-NLS-1$
fOverview= ""; //$NON-NLS-1$
fAntpath= ""; //$NON-NLS-1$
fDestination= ""; //$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;
loadLinksFromDialogSettings(null);
}
private void loadStore(Element element, IDialogSettings settings) {
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= destination;
fFromStandard= true;
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
if (destination.equals("")) { //$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.equals("") && !fDocletname.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$
fFromStandard= false;
} else {
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
}
break;
}
}
}
//find all the links stored in the ant script
boolean firstTime= true;
StringBuffer buf= new StringBuffer();
NodeList children= element.getChildNodes();
for (int i= 0; i < children.getLength(); i++) {
Node child= children.item(i);
if (child.getNodeName().equals("link")) { //$NON-NLS-1$
String href= ((Element) child).getAttribute(HREF);
if (firstTime)
firstTime= false;
else
buf.append(';');
buf.append(href);
}
}
//associate all those links with each project selected
for (Iterator iter= fProjects.iterator(); iter.hasNext();) {
IJavaProject iJavaProject= (IJavaProject) iter.next();
ProjectData data= new ProjectData(iJavaProject);
IPath path= fXmlfile.getLocation();
if (path != null)
data.setAntpath(path.toOSString());
else
data.setAntpath(""); //$NON-NLS-1$
data.setlinks(buf.toString());
data.setDestination(destination);
fLinks.put(iJavaProject, data);
}
//get tree elements
setSelectedElementsFromAnt(element, (IJavaProject) fProjects.get(0));
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= loadbutton(element.getAttribute(USE));
fAuthor= loadbutton(element.getAttribute(AUTHOR));
fVersion= loadbutton(element.getAttribute(VERSION));
fNodeprecated= loadbutton(element.getAttribute(NODEPRECATED));
fNoDeprecatedlist= loadbutton(element.getAttribute(NODEPRECATEDLIST));
fNonavbar= loadbutton(element.getAttribute(NONAVBAR));
fNoindex= loadbutton(element.getAttribute(NOINDEX));
fNotree= loadbutton(element.getAttribute(NOTREE));
fSplitindex= loadbutton(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 void setSelectedElementsFromAnt(Element element, IJavaProject iJavaProject) {
fSelectedElements= new ArrayList();
//get all the packages in side the project
String name;
String packagenames= element.getAttribute(PACKAGENAMES);
if (packagenames != null) {
StringTokenizer tokenizer= new StringTokenizer(packagenames, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
name= tokenizer.nextToken().trim();
IJavaElement el;
try {
el= JavaModelUtil.findTypeContainer(iJavaProject, name);
} catch (JavaModelException e) {
JavaPlugin.log(e);
continue;
}
if ((el != null) && (el instanceof IPackageFragment)) {
fSelectedElements.add(el);
}
}
}
//get all CompilationUnites in side the project
String sourcefiles= element.getAttribute(SOURCEFILES);
if (sourcefiles != null) {
StringTokenizer tokenizer= new StringTokenizer(sourcefiles, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
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)
continue;
IFile[] files= fRoot.findFilesForLocation(path);
for (int i= 0; i < files.length; i++) {
IFile curr= files[i];
if (curr.getProject().equals(iJavaProject.getProject())) {
IJavaElement el= JavaCore.createCompilationUnitFrom(curr);
if (el != null) {
fSelectedElements.add(el);
}
}
}
}
}
}
}
//it is possible that the package list is empty
public StatusInfo getWizardStatus() {
return fWizardStatus;
}
public IJavaElement[] getSelectedElements() {
return (IJavaElement[]) fSelectedElements.toArray(new IJavaElement[fSelectedElements.size()]);
}
public IJavaElement[] getSourceElements() {
return (IJavaElement[]) fSourceElements.toArray(new IJavaElement[fSourceElements.size()]);
}
public String getAccess() {
return fAccess;
}
public String getGeneralAntpath() {
return fAntpath;
}
public String getSpecificAntpath(IJavaProject project) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
return data.getAntPath();
else
return ""; //$NON-NLS-1$
}
public boolean fromStandard() {
return fFromStandard;
}
//for now if multiple projects are selected the destination
//feild will be empty,
public String getDestination(IJavaProject project) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
return data.getDestination();
else
return ""; //$NON-NLS-1$
}
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 IPath[] getClasspath() {
return fClasspath;
}
public IPath[] getSourcepath() {
return fSourcepath;
}
public IWorkspaceRoot getRoot() {
return fRoot;
}
// public IJavaProject[] getJavaProjects() {
// return (IJavaProject[]) fProjects.toArray(new IJavaProject[fProjects.size()]);
// }
//Use only this one later
public List getJavaProjects() {
return fProjects;
}
public String getTitle() {
return fTitle;
}
public String getLinks(IJavaProject project) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
return data.getlinks();
else
return ""; //$NON-NLS-1$
}
public String getDependencies() {
return fDependencies;
}
public Map getLinkMap() {
return fLinks;
}
public boolean doOpenInBrowser() {
return fOpenInBrowser;
}
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 loadbutton(String value) {
if (value == null || value.equals("")) //$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 String[] createArgumentArray() throws CoreException {
if (fProjects.isEmpty()) {
return new String[0];
}
List args= new ArrayList();
args.add(fJDocCommand);
if (fFromStandard) {
args.add("-d"); //$NON-NLS-1$
args.add(fDestination);
} else {
if (!fAdditionalParams.equals("")) { //$NON-NLS-1$
ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$
String[] argsArray= tokens.getProgramArgumentsArray();
for (int i= 0; i < argsArray.length; i++) {
args.add(argsArray[i]);
}
}
args.add("-doclet"); //$NON-NLS-1$
args.add(fDocletname);
args.add("-docletpath"); //$NON-NLS-1$
args.add(fDocletpath);
}
args.add("-sourcepath"); //$NON-NLS-1$
args.add(flatPathList(fSourcepath));
args.add("-classpath"); //$NON-NLS-1$
args.add(flatPathList(fClasspath));
args.add("-" + fAccess); //$NON-NLS-1$
if (fFromStandard) {
if (fJDK14Mode) {
args.add("-source"); //$NON-NLS-1$
args.add("1.4"); //$NON-NLS-1$
}
if (fUse)
args.add("-use"); //$NON-NLS-1$
if (fVersion)
args.add("-version"); //$NON-NLS-1$
if (fAuthor)
args.add("-author"); //$NON-NLS-1$
if (fNonavbar)
args.add("-nonavbar"); //$NON-NLS-1$
if (fNoindex)
args.add("-noindex"); //$NON-NLS-1$
if (fNotree)
args.add("-notree"); //$NON-NLS-1$
if (fNodeprecated)
args.add("-nodeprecated"); //$NON-NLS-1$
if (fNoDeprecatedlist)
args.add("-nodeprecatedlist"); //$NON-NLS-1$
if (fSplitindex)
args.add("-splitindex"); //$NON-NLS-1$
if (!fTitle.equals("")) { //$NON-NLS-1$
args.add("-doctitle"); //$NON-NLS-1$
args.add(fTitle);
}
if (!fStylesheet.equals("")) { //$NON-NLS-1$
args.add("-stylesheetfile"); //$NON-NLS-1$
args.add(fStylesheet);
}
if (!fAdditionalParams.equals("")) { //$NON-NLS-1$
ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$
String[] argsArray= tokens.getProgramArgumentsArray();
for (int i= 0; i < argsArray.length; i++) {
args.add(argsArray[i]);
}
}
String hrefs= (String) fDependencies;
StringTokenizer tokenizer= new StringTokenizer(hrefs, ";"); //$NON-NLS-1$
while (tokenizer.hasMoreElements()) {
String href= (String) tokenizer.nextElement();
args.add("-link"); //$NON-NLS-1$
args.add(href);
}
} //end standard options
if (!fOverview.equals("")) { //$NON-NLS-1$
args.add("-overview"); //$NON-NLS-1$
args.add(fOverview);
}
for (int i= 0; i < fSourceElements.size(); i++) {
IJavaElement curr= (IJavaElement) fSourceElements.get(i);
if (curr instanceof IPackageFragment) {
args.add(curr.getElementName());
} else if (curr instanceof ICompilationUnit) {
IPath p= curr.getResource().getLocation();
if (p != null)
args.add(p.toOSString());
}
}
String[] res= (String[]) args.toArray(new String[args.size()]);
return res;
}
public void createXML() {
FileOutputStream objectStreamOutput= null;
//@change
//for now only writting ant files for single project selection
String antpath= fAntpath;
try {
if (!antpath.equals("")) { //$NON-NLS-1$
File file= new File(antpath);
IPath antPath= new Path(antpath);
IPath antDir= antPath.removeLastSegments(1);
IPath basePath= null;
Assert.isTrue(fProjects.size() == 1);
IJavaProject jproject= (IJavaProject) fProjects.get(0);
IWorkspaceRoot root= jproject.getProject().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, jproject);
writer.writeXML(this);
}
} catch (IOException e) {
JavaPlugin.log(e);
} catch (CoreException e) {
JavaPlugin.log(e);
} finally {
if (objectStreamOutput != null) {
try {
objectStreamOutput.close();
} catch (IOException e) {
}
}
}
}
public IDialogSettings createDialogSettings() {
IDialogSettings settings= new DialogSettings("javadoc"); //$NON-NLS-1$
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.equals("")) //$NON-NLS-1$
settings.put(ANTPATH, fAntpath);
if (!fDestination.equals("")) //$NON-NLS-1$
settings.put(DESTINATION, fDestination);
if (!fAdditionalParams.equals("")) //$NON-NLS-1$
settings.put(EXTRAOPTIONS, fAdditionalParams);
if (!fOverview.equals("")) //$NON-NLS-1$
settings.put(OVERVIEW, fOverview);
if (!fStylesheet.equals("")) //$NON-NLS-1$
settings.put(STYLESHEETFILE, fStylesheet);
if (!fTitle.equals("")) //$NON-NLS-1$
settings.put(TITLE, fTitle);
IDialogSettings links= new DialogSettings("projects"); //$NON-NLS-1$
//Write all project information to DialogSettings.
Set keys= fLinks.keySet();
for (Iterator iter= keys.iterator(); iter.hasNext();) {
IJavaProject iJavaProject= (IJavaProject) iter.next();
IDialogSettings proj= new DialogSettings(iJavaProject.getElementName());
if (!keys.contains(iJavaProject)) {
proj.put(HREF, ""); //$NON-NLS-1$
proj.put(DESTINATION, ""); //$NON-NLS-1$
proj.put(ANTPATH, ""); //$NON-NLS-1$
} else {
ProjectData data= (ProjectData) fLinks.get(iJavaProject);
proj.put(HREF, data.getlinks());
proj.put(DESTINATION, data.getDestination());
proj.put(ANTPATH, data.getAntPath());
}
links.addSection(proj);
}
settings.addSection(links);
return settings;
}
public void setAccess(String access) {
this.fAccess= access;
}
public void setDestination(IJavaProject project, String destination) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
data.setDestination(destination);
}
public void setDestination(String destination) {
fDestination= destination;
}
public void setDocletPath(String docletpath) {
this.fDocletpath= docletpath;
}
public void setDocletName(String docletname) {
this.fDocletname= docletname;
}
public void setStyleSheet(String stylesheet) {
this.fStylesheet= stylesheet;
}
public void setOverview(String overview) {
this.fOverview= overview;
}
public void setAdditionalParams(String params) {
fAdditionalParams= params;
}
public void setSpecificAntpath(IJavaProject project, String antpath) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
data.setAntpath(antpath);
}
public void setGeneralAntpath(String antpath) {
this.fAntpath= antpath;
}
public void setClasspath(IPath[] classpath) {
this.fClasspath= classpath;
}
public void setSourcepath(IPath[] sourcepath) {
this.fSourcepath= sourcepath;
}
public void setSourceElements(IJavaElement[] elements) {
this.fSourceElements= new ArrayList(Arrays.asList(elements));
}
public void setRoot(IWorkspaceRoot root) {
this.fRoot= root;
}
public void setProjects(IJavaProject[] projects, boolean clear) {
if (clear)
fProjects.clear();
for (int i= 0; i < projects.length; i++) {
IJavaProject iJavaProject= projects[i];
if (!fProjects.contains(iJavaProject))
this.fProjects.add(iJavaProject);
}
}
public void setFromStandard(boolean fromStandard) {
this.fFromStandard= fromStandard;
}
public void setTitle(String title) {
this.fTitle= title;
}
public void setDependencies(String dependencies) {
fDependencies= dependencies;
}
public void setLinks(IJavaProject project, String hrefs) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
data.setlinks(hrefs);
}
public void setOpenInBrowser(boolean openInBrowser) {
this.fOpenInBrowser= openInBrowser;
}
public void setBoolean(String flag, boolean value) {
if (flag.equals(AUTHOR))
this.fAuthor= value;
else if (flag.equals(USE))
this.fUse= value;
else if (flag.equals(VERSION))
this.fVersion= value;
else if (flag.equals(NODEPRECATED))
this.fNodeprecated= value;
else if (flag.equals(NODEPRECATEDLIST))
this.fNoDeprecatedlist= value;
else if (flag.equals(NOINDEX))
this.fNoindex= value;
else if (flag.equals(NOTREE))
this.fNotree= value;
else if (flag.equals(SPLITINDEX))
this.fSplitindex= value;
else if (flag.equals(NONAVBAR))
this.fNonavbar= value;
}
public boolean isJDK14Mode() {
return fJDK14Mode;
}
public void setJDK14Mode(boolean jdk14Mode) {
fJDK14Mode= jdk14Mode;
}
private List getValidSelection(ISelection currentSelection) {
ArrayList res= new ArrayList();
if (currentSelection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection= (IStructuredSelection) currentSelection;
if (structuredSelection.isEmpty()) {
currentSelection= JavaPlugin.getActiveWorkbenchWindow().getSelectionService().getSelection();
if (currentSelection instanceof IStructuredSelection)
structuredSelection= (IStructuredSelection) currentSelection;
}
Iterator iter= structuredSelection.iterator();
//this method will also find the project for default
//destination and ant generation paths
getProjects(res, iter);
}
return res;
}
private void getProjects(List selectedElements, Iterator iter) {
while (iter.hasNext()) {
Object selectedElement= iter.next();
IJavaElement elem= getSelectableJavaElement(selectedElement);
if (elem != null) {
IJavaProject jproj= elem.getJavaProject();
if (jproj != null) {
//adding the project of the selected element in the list
//now we can select and generate javadoc for two
//methods in different projects
if (!fProjects.contains(jproj))
fProjects.add(jproj);
selectedElements.add(elem);
}
}
}
//if no projects selected add a default
if (fProjects.isEmpty()) {
try {
IJavaProject[] jprojects= JavaCore.create(fRoot).getJavaProjects();
for (int i= 0; i < jprojects.length; i++) {
IJavaProject iJavaProject= jprojects[i];
if (getValidProject(iJavaProject)) {
fProjects.add(iJavaProject);
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
private IJavaElement getSelectableJavaElement(Object obj) {
IJavaElement je= null;
try {
if (obj instanceof IAdaptable) {
je= (IJavaElement) ((IAdaptable) obj).getAdapter(IJavaElement.class);
}
if (je == null) {
return 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) {
if (cu.isWorkingCopy()) {
cu= (ICompilationUnit) cu.getOriginalElement();
}
return cu;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
IJavaProject project= je.getJavaProject();
if (getValidProject(project))
return project;
else
return null;
}
private boolean getValidProject(IJavaProject project) {
if (project != null) {
try {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (containsCompilationUnits(roots[i])) {
return true;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
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;
}
private class ProjectData {
private IJavaProject dataProject;
private String dataHrefs;
private String dataDestdir;
private String dataAntPath;
ProjectData(IJavaProject project) {
dataProject= project;
}
public void setlinks(String hrefs) {
if (hrefs == null)
dataHrefs= ""; //$NON-NLS-1$
else
dataHrefs= hrefs;
}
public void setDestination(String destination) {
if (destination == null)
dataDestdir= ""; //$NON-NLS-1$
else
dataDestdir= destination;
}
public void setAntpath(String antpath) {
if (antpath == null)
dataAntPath= ""; //$NON-NLS-1$
else
dataAntPath= antpath;
}
public String getlinks() {
return dataHrefs;
}
public String getDestination() {
return dataDestdir;
}
public String getAntPath() {
return dataAntPath;
}
}
}
|
33,356 |
Bug 33356 Read Only files: 2 dialogs from 'override methods' [code manipulation]
|
rc1 1. set a file to read-only 2. open the file in the editor, select an import statement 3. invoke 'override/implement methods' from the context menu 4. error dialog shows up, 'file is read only', press ok 5. second dialog comes up, invalid selection, select type...
|
resolved fixed
|
afbcad0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-28T22:13:30Z | 2003-02-26T20:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OverrideMethodsAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.OverrideMethodQuery;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* Adds unimplemented methods of a type. Action opens a dialog from
* which the user can chosse the methods to be added.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OverrideMethodsAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
/**
* Creates a new <code>OverrideMethodsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public OverrideMethodsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("OverrideMethodsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("OverrideMethodsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("OverrideMethodsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OverrideMethodsAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(checkEnabledEditor());
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
boolean enabled= false;
try {
enabled= getSelectedType(selection) != null;
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
}
setEnabled(enabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
Shell shell= getShell();
try {
IType type= getSelectedType(selection);
if (type == null || !ElementValidator.check(type, getShell(), getDialogTitle(), false)) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.error.type_removed_in_editor")); //$NON-NLS-1$
return;
}
run(shell, type, editor);
} catch (CoreException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
}
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
private boolean checkEnabledEditor() {
return fEditor != null && SelectionConverter.canOperateOn(fEditor);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
Shell shell= getShell();
try {
IType type= SelectionConverter.getTypeAtOffset(fEditor);
if (type != null && ElementValidator.check(type, getShell(), getDialogTitle(), true))
run(shell, type, fEditor);
else
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.not_applicable")); //$NON-NLS-1$
} catch (JavaModelException e) {
JavaPlugin.log(e);
ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
}
}
//---- Helpers -------------------------------------------------------------------
private void run(Shell shell, IType type, IEditorPart editor) {
if (!ActionUtil.isProcessable(getShell(), type)) {
return;
}
OverrideMethodQuery selectionQuery= new OverrideMethodQuery(shell, false);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedMethodsOperation op= new AddUnimplementedMethodsOperation(type, settings, selectionQuery, false);
try {
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.error.nothing_found")); //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
}
private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
Object[] elements= selection.toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("OverrideMethodsAction.error.title"); //$NON-NLS-1$
}
}
|
32,987 |
Bug 32987 Cannot resolve interfaces in same file
|
in the same file create the following and create an anonymous inner class using the Ctrl+Space mechanism for the Xtra interface: public class Test3 { void method() { Xtra x = new Xtra(); //<-- select anonymous inner class for this using // Ctrl+space } } interface Xtra { public void method(); } result: ------------------------ package org.test; public class Test3 { void method() { Xtra x= new Xtra() { }; } } interface Xtra { public void method(); } -------------------------- as you can see the method method() is missing from the anonymous Xtra inteface!
|
resolved fixed
|
31f0e98
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-01T21:15:50Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
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.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
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.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.OverrideMethodQuery;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class AnonymousTypeCompletionProposal extends JavaTypeCompletionProposal {
private IType fDeclaringType;
public AnonymousTypeCompletionProposal(IJavaProject jproject, ICompilationUnit cu, int start, int length, String constructorCompletion, String displayName, String declaringTypeName, int relevance) {
super(constructorCompletion, cu, start, length, null, displayName, relevance);
Assert.isNotNull(declaringTypeName);
Assert.isNotNull(jproject);
fDeclaringType= getDeclaringType(jproject, declaringTypeName);
setImage(getImageForType(fDeclaringType));
setCursorPosition(constructorCompletion.indexOf('(') + 1);
}
private Image getImageForType(IType type) {
String imageName= JavaPluginImages.IMG_OBJS_CLASS; // default
if (type != null) {
try {
if (type.isInterface()) {
imageName= JavaPluginImages.IMG_OBJS_INTERFACE;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return JavaPluginImages.get(imageName);
}
private IType getDeclaringType(IJavaProject project, String typeName) {
try {
return project.findType(typeName);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
/* (non-Javadoc)
* @see JavaTypeCompletionProposal#updateReplacementString(char, int, ImportsStructure)
*/
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
String replacementString= getReplacementString();
// construct replacement text
StringBuffer buf= new StringBuffer();
buf.append(replacementString);
if (!replacementString.endsWith(")")) { //$NON-NLS-1$
buf.append(')');
}
buf.append(" {\n"); //$NON-NLS-1$
if (!createStubs(buf, impStructure)) {
return false;
}
buf.append("}"); //$NON-NLS-1$
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
int tabWidth= CodeFormatterUtil.getTabWidth();
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int indent= Strings.computeIndent(document.get(region.getOffset(), region.getLength()), tabWidth);
String replacement= StubUtility.codeFormat(buf.toString(), indent, lineDelim);
setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
int pos= offset;
while (pos < document.getLength() && Character.isWhitespace(document.getChar(pos))) {
pos++;
}
if (pos < document.getLength() && document.getChar(pos) == ')') {
setReplacementLength(pos - offset + 1);
}
return true;
}
private boolean createStubs(StringBuffer buf, ImportsStructure imports) throws CoreException {
if (fDeclaringType == null) {
return true;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
settings.createComments= false;
ITypeHierarchy hierarchy= fDeclaringType.newSupertypeHierarchy(null);
OverrideMethodQuery selectionQuery= fDeclaringType.isClass() ? new OverrideMethodQuery(JavaPlugin.getActiveWorkbenchShell(), true) : null;
String[] unimplemented= StubUtility.evalUnimplementedMethods(fDeclaringType, hierarchy, true, settings, selectionQuery, imports);
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
buf.append(unimplemented[i]);
if (i < unimplemented.length - 1) {
buf.append('\n');
}
}
return true;
}
return false;
}
}
|
32,942 |
Bug 32942 NPE while opening type hierarchy view
|
Build RC1 Selected JavaElement#triggerSourceEndOffset(...) method, and pressed F4. Unhandled exception caught in event loop. Reason: !ENTRY org.eclipse.ui 4 0 Feb 25, 2003 14:33:54.382 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.updateInput (TypeHierarchyViewPart.java:471) at org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart.setInputElement (TypeHierarchyViewPart.java:439) at org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil.openInViewPart (OpenTypeHierarchyUtil.java:94) at org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil.open (OpenTypeHierarchyUtil.java:75) at org.eclipse.jdt.ui.actions.OpenTypeHierarchyAction.run (OpenTypeHierarchyAction.java:175) at org.eclipse.jdt.ui.actions.OpenTypeHierarchyAction.run (OpenTypeHierarchyAction.java:141) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:841) at org.eclipse.ui.internal.WWinKeyBindingService.pressed (WWinKeyBindingService.java:146) at org.eclipse.ui.internal.WWinKeyBindingService$5.widgetSelected (WWinKeyBindingService.java:327) at org.eclipse.ui.internal.AcceleratorMenu$2.handleEvent (AcceleratorMenu.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1775) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1483) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1271) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1254) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) java.lang.NullPointerException
|
resolved fixed
|
401732f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-01T21:42:22Z | 2003-02-25T13:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.DragSource;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.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.PartInitException;
import org.eclipse.ui.actions.ActionContext;
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.corext.util.JavaModelUtil;
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.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
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.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;
/**
* 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 fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
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;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fHierarchyLifeCycle.setReconciled(isReconciled);
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) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* 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) {
if (member.getElementType() != IJavaElement.TYPE) {
// methods are working copies
if (fHierarchyLifeCycle.isReconciled()) {
member= JavaModelUtil.toWorkingCopy(member);
}
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();
}
// types are originals
member= JavaModelUtil.toOriginal(member);
if (!member.equals(fSelectedType)) {
getCurrentViewer().setSelection(new StructuredSelection(member), 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();
}
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(element);
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();
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
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;
}
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer(true);
}
IType root= getSelectableType(fInputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
fPagebook.showPage(fTypeMethodsSplitter);
}
}
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();
fMethodsViewer.dispose();
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.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) {
updateHierarchyViewer(false);
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
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.addSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
}
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.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
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){
Control control= viewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// 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$
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 < fToggleOrientationActions.length; i++) {
viewMenu.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);
IJavaElement input= 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 RefactorActionGroup(this),
new GenerateActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
initDragAndDrop();
}
/**
* 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.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(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());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
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) {
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) {
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 pagae
// 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(false);
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;
}
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
}
});
}
}
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
fMethodsViewer.refresh();
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 } );
}
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) input;
if (elem instanceof IMember) {
return elem;
} else {
int kind= elem.getElementType();
if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) {
return elem;
}
}
}
return null;
}
/*
* @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());
}
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;
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) {
doTypeHierarchyChanged(fHierarchyLifeCycle, 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);
}
}
}
}
|
32,943 |
Bug 32943 Hierarchy view should better group types with locked methods [type hierarchy]
|
Build RC1 When locking on a given method, occurrences of such a method are always listed behind subtypes, which is causing the end result to be quite hard to decode: Instead of: A +- foo() +- B +- foo() +- C +- foo() It currently displays: A +- B | +- C | | +- foo() | +- foo() +- foo() which goes backwards, when multiple sibling subtypes exist, the end result is even worse.
|
resolved fixed
|
49b0307
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-01T21:59:02Z | 2003-02-25T13:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HierarchyViewerSorter.java
|
package org.eclipse.jdt.internal.ui.typehierarchy;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMethod;
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.internal.corext.util.JavaModelUtil;
/**
*/
public class HierarchyViewerSorter extends JavaElementSorter {
private TypeHierarchyLifeCycle fHierarchy;
private boolean fSortByDefiningType;
public HierarchyViewerSorter(TypeHierarchyLifeCycle cycle) {
fHierarchy= cycle;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerSorter#category(java.lang.Object)
*/
public int category(Object element) {
int cat= super.category(element) * 2;
if (element instanceof IType) {
ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
if (hierarchy != null) {
IType type= (IType) JavaModelUtil.toOriginal((IType) element);
if (Flags.isInterface(hierarchy.getCachedFlags(type))) {
cat++;
}
}
}
return cat;
}
public boolean isSortByDefiningType() {
return fSortByDefiningType;
}
public void setSortByDefiningType(boolean sortByDefiningType) {
fSortByDefiningType= sortByDefiningType;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerSorter#compare(null, null, null)
*/
public int compare(Viewer viewer, Object e1, Object e2) {
ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
if (fSortByDefiningType && hierarchy != null) {
try {
IType def1= (e1 instanceof IMethod) ? getDefiningType(hierarchy, (IMethod) e1) : null;
IType def2= (e2 instanceof IMethod) ? getDefiningType(hierarchy, (IMethod) e2) : null;
if (def1 != null) {
if (def2 != null) {
if (!def2.equals(def1)) {
return compareInHierarchy(hierarchy, def1, def2);
}
} else {
return -1;
}
} else {
if (def2 != null) {
return 1;
}
}
} catch (JavaModelException e) {
// ignore, default to normal comparison
}
}
return super.compare(viewer, e1, e2);
}
private IType getDefiningType(ITypeHierarchy hierarchy, IMethod method) throws JavaModelException {
IType declaringType= (IType) JavaModelUtil.toOriginal(method.getDeclaringType());
int flags= method.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || method.isConstructor()) {
return null;
}
IMethod res= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, declaringType, method.getElementName(), method.getParameterTypes(), false);
if (res == null || method.equals(res)) {
return null;
}
return res.getDeclaringType();
}
private int compareInHierarchy(ITypeHierarchy hierarchy, IType def1, IType def2) {
if (isSuperType(hierarchy, def1, def2)) {
return 1;
} else if (isSuperType(hierarchy, def2, def1)) {
return -1;
}
// interfaces after classes
int flags1= hierarchy.getCachedFlags(def1);
int flags2= hierarchy.getCachedFlags(def2);
if (Flags.isInterface(flags1)) {
if (!Flags.isInterface(flags2)) {
return 1;
}
} else if (Flags.isInterface(flags2)) {
return -1;
}
String name1= def1.getElementName();
String name2= def2.getElementName();
return getCollator().compare(name1, name2);
}
private boolean isSuperType(ITypeHierarchy hierarchy, IType def1, IType def2) {
IType superType= hierarchy.getSuperclass(def1);
if (superType != null) {
if (superType.equals(def2) || isSuperType(hierarchy, superType, def2)) {
return true;
}
}
IType[] superInterfaces= hierarchy.getAllSuperInterfaces(def1);
for (int i= 0; i < superInterfaces.length; i++) {
IType curr= superInterfaces[i];
if (curr.equals(def2) || isSuperType(hierarchy, curr, def2)) {
return true;
}
}
return false;
}
}
|
33,226 |
Bug 33226 Show In beeps
|
RC1 - JUnit setup - select TestCase in package explorer - open TestCase in editor - position cursor right after the package declaration - Show in->Package Explorer Observe: you hear a beep. Normally beeps indicate an error but TestCase is correctly selected since it was before executung Show In.
|
resolved fixed
|
8b674f6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:19:51Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart
implements ISetSelectionTarget, IMenuListener,
IShowInTarget,
IPackagesViewPart, IPropertyChangeListener,
IViewPartInputProvider {
private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical
private static final int HIERARCHICAL_LAYOUT= 0x1;
private static final int FLAT_LAYOUT= 0x2;
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$
private PackageExplorerContentProvider fContentProvider;
private 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();
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= createViewer(parent);
fViewer.setUseHashlookup(true);
fViewer.setComparer(new PackageExplorerElementComparer());
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());
initDragAndDrop();
initKeyListener();
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(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();
}
/**
* This viewer ensures that non-leaves in the hierarchical
* layout are not removed by any filters.
*
* @since 2.1
*/
private ProblemTreeViewer createViewer(Composite parent) {
return new ProblemTreeViewer(parent, 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;
}
};
}
/**
* Answers whether this part shows the packages flat or hierarchical.
*
* @since 2.1
*/
boolean isFlatLayout() {
return fIsCurrentLayoutFlat;
}
private void setProviders() {
//content provider must be set before the label provider
fContentProvider= createContentProvider();
fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setContentProvider(fContentProvider);
fLabelProvider= createLabelProvider();
fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false));
// problem decoration provided by PackageLabelProvider
}
void toggleLayout() {
// Update current state and inform content and label providers
fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat;
saveLayoutState(null);
fContentProvider.setIsFlatLayout(isFlatLayout());
fLabelProvider.setIsFlatLayout(isFlatLayout());
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
/**
* This method should only be called inside this class
* and from test cases.
*/
public PackageExplorerContentProvider createContentProvider() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
return new PackageExplorerContentProvider(showCUChildren, reconcile);
}
private PackageExplorerLabelProvider createLabelProvider() {
return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
fContentProvider);
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillActionBars(actionBars);
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
IJavaElement element= JavaCore.create((IContainer)input);
if (element != null && element.exists())
return element;
return input;
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
if (element instanceof IJavaModel)
result= PackagesMessages.getString("PackageExplorerPart.workspace"); //$NON-NLS-1$
else
result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
if (fWorkingSetName == null)
return result;
String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
fActionSet.setContext(new ActionContext(getSelection()));
fActionSet.fillContextMenu(menu);
fActionSet.setContext(null);
}
private void makeActions() {
fActionSet= new PackageExplorerActionGroup(this);
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners) {
public void dragStart(DragSourceEvent event) {
IStructuredSelection selection= (IStructuredSelection)getSelection();
if (selection.isEmpty()) {
event.doit= false;
return;
}
for (Iterator iter= selection.iterator(); iter.hasNext(); ) {
if (iter.next() instanceof IMember) {
setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)});
break;
}
}
super.dragStart(event);
}
});
}
/**
* 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 (OpenStrategy.getOpenMethod() != OpenStrategy.SINGLE_CLICK)
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 IResource) {
IJavaElement jElement= JavaCore.create((IResource)o);
if (jElement != null && jElement.exists())
elements[i]= jElement;
}
}
return new StructuredSelection(elements);
}
private boolean containsResources(Object[] elements) {
for (int i = 0; i < elements.length; i++) {
if (elements[i] instanceof IResource)
return true;
}
return false;
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
/**
* Initializes the linking enabled setting from the preference store.
*/
private void initLinkingEnabled() {
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR);
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
// ignore selection changes if the package explorer is not the active part.
// In this case the selection change isn't triggered by a user.
if (!isActivePart())
return;
Object obj= selection.getFirstElement();
if (selection.size() == 1) {
IEditorPart part= EditorUtility.isOpenInEditor(obj);
if (part != null) {
IWorkbenchPage page= getSite().getPage();
page.bringToTop(part);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) obj);
}
}
}
private boolean isActivePart() {
return this == getSite().getPage().getActivePart();
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveLayoutState(memento);
saveLinkingEnabled(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//saveScrollState(memento, fViewer.getTree());
fActionSet.saveFilterAndSorterState(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, fLinkingEnabled ? 1 : 0);
}
/**
* Saves the current layout state.
*
* @param memento the memento to save the state into or
* <code>null</code> to store the state in the preferences
* @since 2.1
*/
private void saveLayoutState(IMemento memento) {
if (memento != null) {
memento.putInteger(TAG_LAYOUT, getLayoutAsInt());
} else {
//if memento is null save in preference store
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(TAG_LAYOUT, getLayoutAsInt());
}
}
private int getLayoutAsInt() {
if (fIsCurrentLayoutFlat)
return FLAT_LAYOUT;
else
return HIERARCHICAL_LAYOUT;
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getVisibleExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
private void restoreFilterAndSorter() {
fViewer.setSorter(new JavaElementSorter());
if (fMemento != null)
fActionSet.restoreFilterAndSorterState(fMemento);
}
private void restoreUIState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//restoreScrollState(memento, fViewer.getTree());
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR);
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
fActionSet.handleKeyEvent(event);
}
});
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
showInput(getElementOfInput(editor.getEditorInput()));
}
boolean showInput(Object input) {
Object element= null;
if (input instanceof IFile && isOnClassPath((IFile)input)) {
element= JavaCore.create((IFile)input);
}
if (element == null) // try a non Java resource
element= input;
if (element != null) {
ISelection newSelection= new StructuredSelection(element);
if (!fViewer.getSelection().equals(newSelection)) {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection);
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);
}
}
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
return true;
}
}
return false;
}
private boolean isOnClassPath(IFile file) {
IJavaProject jproject= JavaCore.create(file.getProject());
try {
return jproject.isOnClasspath(file);
} catch (JavaModelException e) {
// fall through
}
return false;
}
/**
* 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 ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the TreeViewer.
*/
public TreeViewer getTreeViewer() {
return fViewer;
}
boolean isExpandable(Object element) {
if (fViewer == null)
return false;
return fViewer.isExpandable(element);
}
void setWorkingSetName(String workingSetName) {
fWorkingSetName= workingSetName;
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= fViewer.getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) {
fActionSet.updateActionBars(getViewSite().getActionBars());
boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
} else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
/* (non-Javadoc)
* @see IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
if (fViewer != null) {
return fViewer.getInput();
}
return null;
}
public void collapseAll() {
fViewer.getControl().setRedraw(false);
fViewer.collapseToLevel(getViewPartInput(), TreeViewer.ALL_LEVELS);
fViewer.getControl().setRedraw(true);
}
public PackageExplorerPart() {
initLinkingEnabled();
}
public boolean show(ShowInContext context) {
Object input= context.getInput();
if (input instanceof IEditorInput)
return showInput(getElementOfInput((IEditorInput)context.getInput()));
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 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);
}
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/JUnitCorePlugin.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Julien Ruaux: [email protected]
* Vincent Massol: [email protected]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IProgressMonitor;
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.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchListener;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* The plug-in runtime class for the JUnit plug-in.
*/
public class JUnitPlugin extends AbstractUIPlugin implements ILaunchListener {
/**
* The single instance of this plug-in runtime class.
*/
private static JUnitPlugin fgPlugin= null;
public static final String PLUGIN_ID = "org.eclipse.jdt.junit" ; //$NON-NLS-1$
public static final String ID_EXTENSION_POINT_TESTRUN_LISTENERS= PLUGIN_ID + "." + "testRunListeners"; //$NON-NLS-1$ //$NON-NLS-2$
public final static String TEST_SUPERCLASS_NAME= "junit.framework.TestCase"; //$NON-NLS-1$
public final static String TEST_INTERFACE_NAME= "junit.framework.Test"; //$NON-NLS-1$
private static URL fgIconBaseURL;
/**
* Use to track new launches. We need to do this
* so that we only attach a TestRunner once to a launch.
* Once a test runner is connected it is removed from the set.
*/
private AbstractSet fTrackedLaunches= new HashSet(20);
/**
* Vector storing the registered test run listeners
*/
private Vector testRunListeners;
public JUnitPlugin(IPluginDescriptor desc) {
super(desc);
fgPlugin= this;
String pathSuffix= "icons/full/"; //$NON-NLS-1$
try {
fgIconBaseURL= new URL(getDescriptor().getInstallURL(), pathSuffix);
} catch (MalformedURLException e) {
// do nothing
}
}
public static JUnitPlugin getDefault() {
return fgPlugin;
}
public static Shell getActiveWorkbenchShell() {
IWorkbenchWindow workBenchWindow= getActiveWorkbenchWindow();
if (workBenchWindow == null)
return null;
return workBenchWindow.getShell();
}
/**
* Returns the active workbench window
*
* @return the active workbench window
*/
public static IWorkbenchWindow getActiveWorkbenchWindow() {
if (fgPlugin == null)
return null;
IWorkbench workBench= fgPlugin.getWorkbench();
if (workBench == null)
return null;
return workBench.getActiveWorkbenchWindow();
}
public IWorkbenchPage getActivePage() {
return getActiveWorkbenchWindow().getActivePage();
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
/*
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
JUnitPreferencePage.initializeDefaults(store);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, "Error", e)); //$NON-NLS-1$
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static URL makeIconFileURL(String name) throws MalformedURLException {
if (JUnitPlugin.fgIconBaseURL == null)
throw new MalformedURLException();
return new URL(JUnitPlugin.fgIconBaseURL, name);
}
static ImageDescriptor getImageDescriptor(String relativePath) {
try {
return ImageDescriptor.createFromURL(makeIconFileURL(relativePath));
} catch (MalformedURLException e) {
// should not happen
return ImageDescriptor.getMissingImageDescriptor();
}
}
/*
* @see ILaunchListener#launchRemoved(ILaunch)
*/
public void launchRemoved(ILaunch launch) {
fTrackedLaunches.remove(launch);
TestRunnerViewPart testRunnerViewPart= findAndShowTestRunnerViewPart();
if (testRunnerViewPart != null && launch.equals(testRunnerViewPart.getLastLaunch()))
testRunnerViewPart.reset();
}
/*
* @see ILaunchListener#launchAdded(ILaunch)
*/
public void launchAdded(ILaunch launch) {
fTrackedLaunches.add(launch);
}
public void connectTestRunner(ILaunch launch, IType launchedType, int port) {
TestRunnerViewPart testRunnerViewPart= findAndShowTestRunnerViewPart();
if (testRunnerViewPart != null)
testRunnerViewPart.startTestRunListening(launchedType, port, launch);
}
private TestRunnerViewPart findAndShowTestRunnerViewPart(){
IWorkbench workbench= getWorkbench();
if (workbench == null)
return null;
IWorkbenchWindow activeWorkbenchWindow= workbench.getActiveWorkbenchWindow();
if (activeWorkbenchWindow == null)
return null;
IWorkbenchPage page= activeWorkbenchWindow.getActivePage();
if (page == null)
return null;
try { // show the result view if it isn't shown yet
TestRunnerViewPart testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
// TODO: have force the creation of view part contents
// otherwise the UI will not be updated
if(testRunner == null || ! testRunner.isCreated()) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the result view
page.activate(activePart);
}
return testRunner;
} catch (PartInitException pie) {
log(pie);
return null;
}
}
/*
* @see ILaunchListener#launchChanged(ILaunch)
*/
public void launchChanged(final ILaunch launch) {
if (!fTrackedLaunches.contains(launch))
return;
ILaunchConfiguration config= launch.getLaunchConfiguration();
IType launchedType= null;
int port= -1;
if (config != null) {
// test whether the launch defines the JUnit attributes
String portStr= launch.getAttribute(JUnitBaseLaunchConfiguration.PORT_ATTR);
String typeStr= launch.getAttribute(JUnitBaseLaunchConfiguration.TESTTYPE_ATTR);
if (portStr != null && typeStr != null) {
port= Integer.parseInt(portStr);
IJavaElement element= JavaCore.create(typeStr);
if (element instanceof IType)
launchedType= (IType)element;
}
}
if (launchedType != null) {
fTrackedLaunches.remove(launch);
final int finalPort= port;
final IType finalType= launchedType;
getDisplay().asyncExec(new Runnable() {
public void run() {
connectTestRunner(launch, finalType, finalPort);
}
});
}
}
/*
* @see Plugin#startup()
*/
public void startup() throws CoreException {
super.startup();
ILaunchManager launchManager= DebugPlugin.getDefault().getLaunchManager();
launchManager.addLaunchListener(this);
}
/*
* @see Plugin#shutdown()
*/
public void shutdown() throws CoreException {
super.shutdown();
ILaunchManager launchManager= DebugPlugin.getDefault().getLaunchManager();
launchManager.removeLaunchListener(this);
}
public static Display getDisplay() {
Shell shell= getActiveWorkbenchShell();
if (shell != null) {
return shell.getDisplay();
}
Display display= Display.getCurrent();
if (display == null) {
display= Display.getDefault();
}
return display;
}
/**
* Utility method to create and return a selection dialog that allows
* selection of a specific Java package. Empty packages are not returned.
* If Java Projects are provided, only packages found within those projects
* are included. If no Java projects are provided, all Java projects in the
* workspace are considered.
*/
public static ElementListSelectionDialog createAllPackagesDialog(Shell shell, IJavaProject[] originals, final boolean includeDefaultPackage) throws JavaModelException {
final List packageList= new ArrayList();
if (originals == null) {
IWorkspaceRoot wsroot= ResourcesPlugin.getWorkspace().getRoot();
IJavaModel model= JavaCore.create(wsroot);
originals= model.getJavaProjects();
}
final IJavaProject[] projects= originals;
final JavaModelException[] exception= new JavaModelException[1];
ProgressMonitorDialog monitor= new ProgressMonitorDialog(shell);
IRunnableWithProgress r= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
Set packageNameSet= new HashSet();
monitor.beginTask(JUnitMessages.getString("JUnitPlugin.searching"), projects.length); //$NON-NLS-1$
for (int i= 0; i < projects.length; i++) {
IPackageFragment[] pkgs= projects[i].getPackageFragments();
for (int j= 0; j < pkgs.length; j++) {
IPackageFragment pkg= pkgs[j];
if (!pkg.hasChildren() && (pkg.getNonJavaResources().length > 0))
continue;
String pkgName= pkg.getElementName();
if (!includeDefaultPackage && pkgName.length() == 0)
continue;
if (packageNameSet.add(pkgName))
packageList.add(pkg);
}
monitor.worked(1);
}
monitor.done();
} catch (JavaModelException jme) {
exception[0]= jme;
}
}
};
try {
monitor.run(false, false, r);
} catch (InvocationTargetException e) {
JUnitPlugin.log(e);
} catch (InterruptedException e) {
JUnitPlugin.log(e);
}
if (exception[0] != null)
throw exception[0];
int flags= JavaElementLabelProvider.SHOW_DEFAULT;
ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaElementLabelProvider(flags));
dialog.setIgnoreCase(false);
dialog.setElements(packageList.toArray()); // XXX inefficient
return dialog;
}
/**
* Initializes TestRun Listener extensions
*/
private void loadTestRunListeners() {
testRunListeners= new Vector();
IExtensionPoint extensionPoint= Platform.getPluginRegistry().getExtensionPoint(ID_EXTENSION_POINT_TESTRUN_LISTENERS);
if (extensionPoint == null) {
return;
}
IConfigurationElement[] configs= extensionPoint.getConfigurationElements();
MultiStatus status= new MultiStatus(PLUGIN_ID, IStatus.OK, "Could not load some testRunner extension points", null); //$NON-NLS-1$
for (int i= 0; i < configs.length; i++) {
try {
ITestRunListener testRunListener= (ITestRunListener) configs[i].createExecutableExtension("class"); //$NON-NLS-1$
testRunListeners.add(testRunListener);
} catch (CoreException e) {
status.add(e.getStatus());
}
}
if (!status.isOK()) {
JUnitPlugin.log(status);
}
}
/**
* Returns an array of all TestRun listeners
*/
public Vector getTestRunListeners() {
if (testRunListeners == null) {
loadTestRunListeners();
}
return testRunListeners;
}
/**
* Adds a TestRun listener to the collection of listeners
*/
public void addTestRunListener(ITestRunListener newListener) {
if (testRunListeners == null) {
loadTestRunListeners();
}
testRunListeners.add(newListener);
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CounterPanel.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* A panel with counters for the number of Runs, Errors and Failures.
*/
public class CounterPanel extends Composite {
private Text fNumberOfErrors;
private Text fNumberOfFailures;
private Text fNumberOfRuns;
private int fTotal;
private final Image fErrorIcon= TestRunnerViewPart.createImage("ovr16/error_ovr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("ovr16/failed_ovr.gif"); //$NON-NLS-1$
public CounterPanel(Composite parent) {
super(parent, SWT.WRAP);
GridLayout gridLayout= new GridLayout();
gridLayout.numColumns= 9;
gridLayout.makeColumnsEqualWidth= false;
gridLayout.marginWidth= 0;
setLayout(gridLayout);
fNumberOfRuns= createLabel(JUnitMessages.getString("CounterPanel.label.runs"), null, " 0/0 "); //$NON-NLS-1$ //$NON-NLS-2$
fNumberOfErrors= createLabel(JUnitMessages.getString("CounterPanel.label.errors"), fErrorIcon, " 0 "); //$NON-NLS-1$ //$NON-NLS-2$
fNumberOfFailures= createLabel(JUnitMessages.getString("CounterPanel.label.failures"), fFailureIcon, " 0 "); //$NON-NLS-1$ //$NON-NLS-2$
addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
}
private Text createLabel(String name, Image image, String init) {
Label label= new Label(this, SWT.NONE);
if (image != null) {
image.setBackground(label.getBackground());
label.setImage(image);
}
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
label= new Label(this, SWT.NONE);
label.setText(name);
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
Text value= new Text(this, SWT.READ_ONLY);
value.setText(init);
value.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING));
return value;
}
public void reset() {
setErrorValue(0);
setFailureValue(0);
setRunValue(0);
fTotal= 0;
}
public void setTotal(int value) {
fTotal= value;
}
public int getTotal(){
return fTotal;
}
public void setRunValue(int value) {
String runString= JUnitMessages.getFormattedString("CounterPanel.runcount", new String[] { Integer.toString(value), Integer.toString(fTotal) }); //$NON-NLS-1$
fNumberOfRuns.setText(runString);
fNumberOfRuns.redraw();
redraw();
}
public void setErrorValue(int value) {
fNumberOfErrors.setText(Integer.toString(value));
redraw();
}
public void setFailureValue(int value) {
fNumberOfFailures.setText(Integer.toString(value));
redraw();
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A view presenting the failed tests in a table.
*/
class FailureRunView implements ITestRunView, IMenuListener {
private Table fTable;
private TestRunnerViewPart fRunnerViewPart;
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fFailureTabIcon= TestRunnerViewPart.createImage("obj16/failures.gif"); //$NON-NLS-1$
public FailureRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fRunnerViewPart= runner;
CTabItem failureTab= new CTabItem(tabFolder, SWT.NONE);
failureTab.setText(getName());
failureTab.setImage(fFailureTabIcon);
Composite composite= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
composite.setLayout(gridLayout);
GridData gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
composite.setLayoutData(gridData);
fTable= new Table(composite, SWT.NONE);
gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
fTable.setLayout(gridLayout);
gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTable.setLayoutData(gridData);
failureTab.setControl(composite);
failureTab.setToolTipText(JUnitMessages.getString("FailureRunView.tab.tooltip")); //$NON-NLS-1$
initMenu();
addListeners();
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fFailureTabIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTable);
fTable.setMenu(menu);
}
public String getName() {
return JUnitMessages.getString("FailureRunView.tab.title"); //$NON-NLS-1$
}
public String getSelectedTestId() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return getTestInfo(fTable.getItem(index)).fTestId;
}
private String getClassName() {
return cutFromTo(getSelectedText(), '(', ')');
}
private String getMethodName() {
return cutTo(getSelectedText(), '(');
}
private static String cutFromTo(String string, char from, char to){
String modified= string;
modified= modified.substring(modified.indexOf(from) + 1);
return cutTo(modified, to);
}
private static String cutTo(String string, char to){
int toIndex= string.indexOf(to);
if (toIndex == -1)
return string;
else
return string.substring(0, toIndex);
}
public void menuAboutToShow(IMenuManager manager){
if (fTable.getSelectionCount() > 0) {
String className= getClassName();
String methodName= getMethodName();
if (className != null) {
manager.add(new OpenTestAction(fRunnerViewPart, className, methodName));
manager.add(new RerunAction(fRunnerViewPart, getSelectedTestId(), className, methodName));
}
}
}
private String getSelectedText() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return fTable.getItem(index).getText();
}
public void setSelectedTest(String testId){
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
TableItem tableItem= items[i];
TestRunInfo info= getTestInfo(tableItem);
if (info.fTestId.equals(testId)){
fTable.setSelection(new TableItem[] { tableItem });
fTable.showItem(tableItem);
return;
}
}
}
private TestRunInfo getTestInfo(TableItem item) {
return (TestRunInfo)item.getData();
}
public void setFocus() {
fTable.setFocus();
}
public void endTest(String testId){
TestRunInfo testInfo= fRunnerViewPart.getTestInfo(testId);
if(testInfo == null || testInfo.fStatus == ITestRunListener.STATUS_OK)
return;
TableItem tableItem= new TableItem(fTable, SWT.NONE);
updateTableItem(testInfo, tableItem);
fTable.showItem(tableItem);
}
private void updateTableItem(TestRunInfo testInfo, TableItem tableItem) {
tableItem.setText(testInfo.fTestName);
if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE)
tableItem.setImage(fFailureIcon);
else
tableItem.setImage(fErrorIcon);
tableItem.setData(testInfo);
}
private TableItem findItem(String testId) {
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
TestRunInfo info= getTestInfo(items[i]);
if (info.fTestId.equals(testId))
return items[i];
}
return null;
}
public void activate() {
testSelected();
}
public void aboutToStart() {
fTable.removeAll();
}
protected void testSelected() {
fRunnerViewPart.handleTestSelected(getSelectedTestId());
}
protected void addListeners() {
fTable.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTable.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTable.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e){
handleDoubleClick(e);
}
public void mouseDown(MouseEvent e) {
activate();
}
public void mouseUp(MouseEvent e) {
activate();
}
});
}
public void handleDoubleClick(MouseEvent e) {
if (fTable.getSelectionCount() > 0)
new OpenTestAction(fRunnerViewPart, getClassName(), getMethodName()).run();
}
public void newTreeEntry(String treeEntry) {
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo)
*/
public void testStatusChanged(TestRunInfo info) {
TableItem item= findItem(info.fTestId);
if (item != null) {
if (info.fStatus == ITestRunListener.STATUS_OK) {
item.dispose();
return;
}
updateTableItem(info, item);
}
if (item == null && info.fStatus != ITestRunListener.STATUS_OK) {
item= new TableItem(fTable, SWT.NONE);
updateTableItem(info, item);
}
if (item != null)
fTable.showItem(item);
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureTraceView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
/**
* A view that shows a stack trace of a failed test.
*/
class FailureTraceView implements IMenuListener {
private static final String FRAME_PREFIX= "at "; //$NON-NLS-1$
private Table fTable;
private TestRunnerViewPart fTestRunner;
private String fInputTrace;
private final Image fStackIcon= TestRunnerViewPart.createImage("obj16/stkfrm_obj.gif"); //$NON-NLS-1$
private final Image fExceptionIcon= TestRunnerViewPart.createImage("obj16/exc_catch.gif"); //$NON-NLS-1$
public FailureTraceView(Composite parent, TestRunnerViewPart testRunner) {
fTable= new Table(parent, SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL);
fTestRunner= testRunner;
fTable.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e){
handleDoubleClick(e);
}
});
initMenu();
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
}
void handleDoubleClick(MouseEvent e) {
if(fTable.getSelection().length != 0) {
Action a= createOpenEditorAction(getSelectedText());
if (a != null)
a.run();
}
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTable);
fTable.setMenu(menu);
}
public void menuAboutToShow(IMenuManager manager) {
if (fTable.getSelectionCount() > 0) {
Action a= createOpenEditorAction(getSelectedText());
if (a != null)
manager.add(a);
}
manager.add(new CopyTraceAction(FailureTraceView.this));
}
public String getTrace() {
return fInputTrace;
}
private String getSelectedText() {
return fTable.getSelection()[0].getText();
}
private Action createOpenEditorAction(String traceLine) {
try {
//TODO: works for JDK stack trace only
String testName= traceLine;
testName= testName.substring(testName.indexOf(FRAME_PREFIX)); //$NON-NLS-1$
testName= testName.substring(FRAME_PREFIX.length(), testName.indexOf('(')).trim();
testName= testName.substring(0, testName.lastIndexOf('.'));
int innerSeparatorIndex= testName.indexOf('$');
if (innerSeparatorIndex != -1)
testName= testName.substring(0, innerSeparatorIndex);
String lineNumber= traceLine;
lineNumber= lineNumber.substring(lineNumber.indexOf(':') + 1, lineNumber.indexOf(")")); //$NON-NLS-1$
int line= Integer.valueOf(lineNumber).intValue();
return new OpenEditorAtLineAction(fTestRunner, testName, line);
} catch(NumberFormatException e) {
}
catch(IndexOutOfBoundsException e) {
}
return null;
}
void disposeIcons(){
if (fExceptionIcon != null && !fExceptionIcon.isDisposed())
fExceptionIcon.dispose();
if (fStackIcon != null && !fStackIcon.isDisposed())
fStackIcon.dispose();
}
/**
* Returns the composite used to present the trace
*/
public Composite getComposite(){
return fTable;
}
/**
* Refresh the table from the the trace.
*/
public void refresh() {
updateTable(fInputTrace);
}
/**
* Shows a TestFailure
*/
public void showFailure(String trace) {
if (fInputTrace == trace)
return;
fInputTrace= trace;
updateTable(trace);
}
private void updateTable(String trace) {
if(trace == null || trace.trim().equals("")) { //$NON-NLS-1$
clear();
return;
}
trace= trace.trim();
fTable.setRedraw(false);
fTable.removeAll();
fillTable(filterStack(trace));
fTable.setRedraw(true);
}
protected void fillTable(String trace) {
StringReader stringReader= new StringReader(trace);
BufferedReader bufferedReader= new BufferedReader(stringReader);
String line;
try {
// first line contains the thrown exception
line= bufferedReader.readLine();
if (line == null)
return;
TableItem tableItem= new TableItem(fTable, SWT.NONE);
String itemLabel= line.replace('\t', ' ');
tableItem.setText(itemLabel);
tableItem.setImage(fExceptionIcon);
// the stack frames of the trace
while ((line= bufferedReader.readLine()) != null) {
itemLabel= line.replace('\t', ' ');
tableItem= new TableItem(fTable, SWT.NONE);
// heuristic for detecting a stack frame - works for JDK
if ((itemLabel.indexOf(" at ") >= 0)) { //$NON-NLS-1$
tableItem.setImage(fStackIcon);
}
tableItem.setText(itemLabel);
}
} catch (IOException e) {
TableItem tableItem= new TableItem(fTable, SWT.NONE);
tableItem.setText(trace);
}
}
/**
* Shows other information than a stack trace.
*/
public void setInformation(String text) {
clear();
TableItem tableItem= new TableItem(fTable, SWT.NONE);
tableItem.setText(text);
}
/**
* Clears the non-stack trace info
*/
public void clear() {
fTable.removeAll();
fInputTrace= null;
}
private String filterStack(String stackTrace) {
if (!JUnitPreferencePage.getFilterStack() || stackTrace == null)
return stackTrace;
StringWriter stringWriter= new StringWriter();
PrintWriter printWriter= new PrintWriter(stringWriter);
StringReader stringReader= new StringReader(stackTrace);
BufferedReader bufferedReader= new BufferedReader(stringReader);
String line;
String[] patterns= JUnitPreferencePage.getFilterPatterns();
try {
while ((line= bufferedReader.readLine()) != null) {
if (!filterLine(patterns, line))
printWriter.println(line);
}
} catch (IOException e) {
return stackTrace; // return the stack unfiltered
}
return stringWriter.toString();
}
private boolean filterLine(String[] patterns, String line) {
String pattern;
int len;
for (int i= (patterns.length - 1); i >= 0; --i) {
pattern= patterns[i];
len= pattern.length() - 1;
if (pattern.charAt(len) == '*') {
//strip trailing * from a package filter
pattern= pattern.substring(0, len);
} else if (Character.isUpperCase(pattern.charAt(0))) {
//class in the default package
pattern= FRAME_PREFIX + pattern + '.';
} else {
//class names start w/ an uppercase letter after the .
final int lastDotIndex= pattern.lastIndexOf('.');
if ((lastDotIndex != -1) && (lastDotIndex != len) && Character.isUpperCase(pattern.charAt(lastDotIndex + 1)))
pattern += '.'; //append . to a class filter
}
if (line.indexOf(pattern) > 0)
return true;
}
return false;
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/HierarchyRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/*
* A view that shows the contents of a test suite
* as a tree.
*/
class HierarchyRunView implements ITestRunView, IMenuListener {
/**
* The tree widget
*/
private Tree fTree;
public static final int IS_SUITE= -1;
/**
* Helper used to resurrect test hierarchy
*/
private static class SuiteInfo {
public int fTestCount;
public TreeItem fTreeItem;
public SuiteInfo(TreeItem treeItem, int testCount){
fTreeItem= treeItem;
fTestCount= testCount;
}
}
/**
* Vector of SuiteInfo items
*/
private Vector fSuiteInfos= new Vector();
/**
* Maps test Ids to TreeItems.
*/
private Map fTreeItemMap= new HashMap();
private TestRunnerViewPart fTestRunnerPart;
private final Image fOkIcon= TestRunnerViewPart.createImage("obj16/testok.gif"); //$NON-NLS-1$
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fHierarchyIcon= TestRunnerViewPart.createImage("obj16/testhier.gif"); //$NON-NLS-1$
private final Image fSuiteIcon= TestRunnerViewPart.createImage("obj16/tsuite.gif"); //$NON-NLS-1$
private final Image fSuiteErrorIcon= TestRunnerViewPart.createImage("obj16/tsuiteerror.gif"); //$NON-NLS-1$
private final Image fSuiteFailIcon= TestRunnerViewPart.createImage("obj16/tsuitefail.gif"); //$NON-NLS-1$
private final Image fTestIcon= TestRunnerViewPart.createImage("obj16/test.gif"); //$NON-NLS-1$
public HierarchyRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fTestRunnerPart= runner;
CTabItem hierarchyTab= new CTabItem(tabFolder, SWT.NONE);
hierarchyTab.setText(getName());
hierarchyTab.setImage(fHierarchyIcon);
Composite testTreePanel= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
testTreePanel.setLayout(gridLayout);
GridData gridData= new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
testTreePanel.setLayoutData(gridData);
hierarchyTab.setControl(testTreePanel);
hierarchyTab.setToolTipText(JUnitMessages.getString("HierarchyRunView.tab.tooltip")); //$NON-NLS-1$
fTree= new Tree(testTreePanel, SWT.V_SCROLL);
gridData= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTree.setLayoutData(gridData);
initMenu();
addListeners();
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fOkIcon.dispose();
fHierarchyIcon.dispose();
fTestIcon.dispose();
fSuiteIcon.dispose();
fSuiteErrorIcon.dispose();
fSuiteFailIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTree);
fTree.setMenu(menu);
}
private String getTestLabel() {
TreeItem treeItem= fTree.getSelection()[0];
if(treeItem == null)
return ""; //$NON-NLS-1$
return treeItem.getText();
}
private TestRunInfo getTestInfo() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length == 0)
return null;
return ((TestRunInfo)treeItems[0].getData());
}
private String getClassName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return extractClassName(testInfo.fTestName);
}
public String getSelectedTestId() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return testInfo.fTestId;
}
private String extractClassName(String testNameString) {
if (testNameString == null)
return null;
int index= testNameString.indexOf('(');
if (index < 0)
return testNameString;
testNameString= testNameString.substring(index + 1);
return testNameString.substring(0, testNameString.indexOf(')'));
}
public String getName() {
return JUnitMessages.getString("HierarchyRunView.tab.title"); //$NON-NLS-1$
}
public void setSelectedTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
if (treeItem != null)
fTree.setSelection(new TreeItem[]{treeItem});
}
public void endTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
// workaround for bug 8657
if (treeItem == null)
return;
TestRunInfo testInfo= fTestRunnerPart.getTestInfo(testId);
updateItem(treeItem, testInfo);
if (testInfo.fTrace != null)
fTree.showItem(treeItem);
}
private void updateItem(TreeItem treeItem, TestRunInfo testInfo) {
treeItem.setData(testInfo);
if(testInfo.fStatus == ITestRunListener.STATUS_OK) {
treeItem.setImage(fOkIcon);
return;
}
if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE)
treeItem.setImage(fFailureIcon);
else if (testInfo.fStatus == ITestRunListener.STATUS_ERROR)
treeItem.setImage(fErrorIcon);
propagateStatus(treeItem, testInfo.fStatus);
}
void propagateStatus(TreeItem item, int status) {
TreeItem parent= item.getParentItem();
if (parent == null)
return;
Image parentImage= parent.getImage();
if (status == ITestRunListener.STATUS_FAILURE) {
if (parentImage == fSuiteErrorIcon || parentImage == fSuiteFailIcon)
return;
parent.setImage(fSuiteFailIcon);
} else {
if (parentImage == fSuiteErrorIcon)
return;
parent.setImage(fSuiteErrorIcon);
}
propagateStatus(parent, status);
}
public void activate() {
testSelected();
}
public void setFocus() {
fTree.setFocus();
}
public void aboutToStart() {
fTree.removeAll();
fSuiteInfos.removeAllElements();
fTreeItemMap= new HashMap();
}
protected void testSelected() {
fTestRunnerPart.handleTestSelected(getSelectedTestId());
}
public void menuAboutToShow(IMenuManager manager) {
if (fTree.getSelectionCount() > 0) {
final TreeItem treeItem= fTree.getSelection()[0];
TestRunInfo testInfo= (TestRunInfo) treeItem.getData();
if (testInfo.fStatus == IS_SUITE) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
manager.add(new OpenTestAction(fTestRunnerPart, className));
} else {
manager.add(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel()));
manager.add(new RerunAction(fTestRunnerPart, getSelectedTestId(), getClassName(), getTestLabel()));
}
}
}
private void addListeners() {
fTree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTree.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTree.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e) {
handleDoubleClick(e);
}
});
}
void handleDoubleClick(MouseEvent e) {
TestRunInfo testInfo= getTestInfo();
if(testInfo == null)
return;
if ((testInfo.fStatus == IS_SUITE)) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
(new OpenTestAction(fTestRunnerPart, className)).run();
}
else {
(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel())).run();
}
}
public void newTreeEntry(String treeEntry) {
// format: testId","testName","isSuite","testcount
int index0= treeEntry.indexOf(',');
int index1= treeEntry.indexOf(',', index0+1);
int index2= treeEntry.indexOf(',', index1+1);
String label= treeEntry.substring(index0+1, index1).trim();
String id= treeEntry.substring(0, index0);
TestRunInfo testInfo= new TestRunInfo(id, label);
//fTestInfo.addElement(testInfo);
int index3;
if((index3= label.indexOf('(')) > 0)
label= label.substring(0, index3);
if((index3= label.indexOf('@')) > 0)
label= label.substring(0, index3);
String isSuite= treeEntry.substring(index1+1, index2);
int testCount= Integer.parseInt(treeEntry.substring(index2+1));
TreeItem treeItem;
while((fSuiteInfos.size() > 0) && (((SuiteInfo) fSuiteInfos.lastElement()).fTestCount == 0)) {
fSuiteInfos.removeElementAt(fSuiteInfos.size()-1);
}
if(fSuiteInfos.size() == 0){
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(fTree, SWT.NONE);
treeItem.setImage(fSuiteIcon);
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else if(isSuite.equals("true")) { //$NON-NLS-1$
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fHierarchyIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else {
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fTestIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
mapTest(testInfo, treeItem);
}
treeItem.setText(label);
treeItem.setData(testInfo);
}
private void mapTest(TestRunInfo info, TreeItem item) {
fTreeItemMap.put(info.fTestId, item);
}
private TreeItem findTreeItem(String testId) {
Object o= fTreeItemMap.get(testId);
if (o instanceof TreeItem)
return (TreeItem)o;
return null;
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo, int)
*/
public void testStatusChanged(TestRunInfo newInfo) {
Object o= fTreeItemMap.get(newInfo.fTestId);
if (o instanceof TreeItem) {
updateItem((TreeItem)o, newInfo);
return;
}
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitPlugin.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Julien Ruaux: [email protected]
* Vincent Massol: [email protected]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IProgressMonitor;
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.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchListener;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* The plug-in runtime class for the JUnit plug-in.
*/
public class JUnitPlugin extends AbstractUIPlugin implements ILaunchListener {
/**
* The single instance of this plug-in runtime class.
*/
private static JUnitPlugin fgPlugin= null;
public static final String PLUGIN_ID = "org.eclipse.jdt.junit" ; //$NON-NLS-1$
public static final String ID_EXTENSION_POINT_TESTRUN_LISTENERS= PLUGIN_ID + "." + "testRunListeners"; //$NON-NLS-1$ //$NON-NLS-2$
public final static String TEST_SUPERCLASS_NAME= "junit.framework.TestCase"; //$NON-NLS-1$
public final static String TEST_INTERFACE_NAME= "junit.framework.Test"; //$NON-NLS-1$
private static URL fgIconBaseURL;
/**
* Use to track new launches. We need to do this
* so that we only attach a TestRunner once to a launch.
* Once a test runner is connected it is removed from the set.
*/
private AbstractSet fTrackedLaunches= new HashSet(20);
/**
* Vector storing the registered test run listeners
*/
private Vector testRunListeners;
public JUnitPlugin(IPluginDescriptor desc) {
super(desc);
fgPlugin= this;
String pathSuffix= "icons/full/"; //$NON-NLS-1$
try {
fgIconBaseURL= new URL(getDescriptor().getInstallURL(), pathSuffix);
} catch (MalformedURLException e) {
// do nothing
}
}
public static JUnitPlugin getDefault() {
return fgPlugin;
}
public static Shell getActiveWorkbenchShell() {
IWorkbenchWindow workBenchWindow= getActiveWorkbenchWindow();
if (workBenchWindow == null)
return null;
return workBenchWindow.getShell();
}
/**
* Returns the active workbench window
*
* @return the active workbench window
*/
public static IWorkbenchWindow getActiveWorkbenchWindow() {
if (fgPlugin == null)
return null;
IWorkbench workBench= fgPlugin.getWorkbench();
if (workBench == null)
return null;
return workBench.getActiveWorkbenchWindow();
}
public IWorkbenchPage getActivePage() {
return getActiveWorkbenchWindow().getActivePage();
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
/*
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
JUnitPreferencePage.initializeDefaults(store);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, "Error", e)); //$NON-NLS-1$
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static URL makeIconFileURL(String name) throws MalformedURLException {
if (JUnitPlugin.fgIconBaseURL == null)
throw new MalformedURLException();
return new URL(JUnitPlugin.fgIconBaseURL, name);
}
static ImageDescriptor getImageDescriptor(String relativePath) {
try {
return ImageDescriptor.createFromURL(makeIconFileURL(relativePath));
} catch (MalformedURLException e) {
// should not happen
return ImageDescriptor.getMissingImageDescriptor();
}
}
/*
* @see ILaunchListener#launchRemoved(ILaunch)
*/
public void launchRemoved(ILaunch launch) {
fTrackedLaunches.remove(launch);
TestRunnerViewPart testRunnerViewPart= findAndShowTestRunnerViewPart();
if (testRunnerViewPart != null && launch.equals(testRunnerViewPart.getLastLaunch()))
testRunnerViewPart.reset();
}
/*
* @see ILaunchListener#launchAdded(ILaunch)
*/
public void launchAdded(ILaunch launch) {
fTrackedLaunches.add(launch);
}
public void connectTestRunner(ILaunch launch, IType launchedType, int port) {
TestRunnerViewPart testRunnerViewPart= findAndShowTestRunnerViewPart();
if (testRunnerViewPart != null)
testRunnerViewPart.startTestRunListening(launchedType, port, launch);
}
private TestRunnerViewPart findAndShowTestRunnerViewPart(){
IWorkbench workbench= getWorkbench();
if (workbench == null)
return null;
IWorkbenchWindow activeWorkbenchWindow= workbench.getActiveWorkbenchWindow();
if (activeWorkbenchWindow == null)
return null;
IWorkbenchPage page= activeWorkbenchWindow.getActivePage();
if (page == null)
return null;
try { // show the result view if it isn't shown yet
TestRunnerViewPart testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
// TODO: have force the creation of view part contents
// otherwise the UI will not be updated
if(testRunner == null || ! testRunner.isCreated()) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the result view
page.activate(activePart);
}
return testRunner;
} catch (PartInitException pie) {
log(pie);
return null;
}
}
/*
* @see ILaunchListener#launchChanged(ILaunch)
*/
public void launchChanged(final ILaunch launch) {
if (!fTrackedLaunches.contains(launch))
return;
ILaunchConfiguration config= launch.getLaunchConfiguration();
IType launchedType= null;
int port= -1;
if (config != null) {
// test whether the launch defines the JUnit attributes
String portStr= launch.getAttribute(JUnitBaseLaunchConfiguration.PORT_ATTR);
String typeStr= launch.getAttribute(JUnitBaseLaunchConfiguration.TESTTYPE_ATTR);
if (portStr != null && typeStr != null) {
port= Integer.parseInt(portStr);
IJavaElement element= JavaCore.create(typeStr);
if (element instanceof IType)
launchedType= (IType)element;
}
}
if (launchedType != null) {
fTrackedLaunches.remove(launch);
final int finalPort= port;
final IType finalType= launchedType;
getDisplay().asyncExec(new Runnable() {
public void run() {
connectTestRunner(launch, finalType, finalPort);
}
});
}
}
/*
* @see Plugin#startup()
*/
public void startup() throws CoreException {
super.startup();
ILaunchManager launchManager= DebugPlugin.getDefault().getLaunchManager();
launchManager.addLaunchListener(this);
}
/*
* @see Plugin#shutdown()
*/
public void shutdown() throws CoreException {
super.shutdown();
ILaunchManager launchManager= DebugPlugin.getDefault().getLaunchManager();
launchManager.removeLaunchListener(this);
}
public static Display getDisplay() {
Shell shell= getActiveWorkbenchShell();
if (shell != null) {
return shell.getDisplay();
}
Display display= Display.getCurrent();
if (display == null) {
display= Display.getDefault();
}
return display;
}
/**
* Utility method to create and return a selection dialog that allows
* selection of a specific Java package. Empty packages are not returned.
* If Java Projects are provided, only packages found within those projects
* are included. If no Java projects are provided, all Java projects in the
* workspace are considered.
*/
public static ElementListSelectionDialog createAllPackagesDialog(Shell shell, IJavaProject[] originals, final boolean includeDefaultPackage) throws JavaModelException {
final List packageList= new ArrayList();
if (originals == null) {
IWorkspaceRoot wsroot= ResourcesPlugin.getWorkspace().getRoot();
IJavaModel model= JavaCore.create(wsroot);
originals= model.getJavaProjects();
}
final IJavaProject[] projects= originals;
final JavaModelException[] exception= new JavaModelException[1];
ProgressMonitorDialog monitor= new ProgressMonitorDialog(shell);
IRunnableWithProgress r= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
Set packageNameSet= new HashSet();
monitor.beginTask(JUnitMessages.getString("JUnitPlugin.searching"), projects.length); //$NON-NLS-1$
for (int i= 0; i < projects.length; i++) {
IPackageFragment[] pkgs= projects[i].getPackageFragments();
for (int j= 0; j < pkgs.length; j++) {
IPackageFragment pkg= pkgs[j];
if (!pkg.hasChildren() && (pkg.getNonJavaResources().length > 0))
continue;
String pkgName= pkg.getElementName();
if (!includeDefaultPackage && pkgName.length() == 0)
continue;
if (packageNameSet.add(pkgName))
packageList.add(pkg);
}
monitor.worked(1);
}
monitor.done();
} catch (JavaModelException jme) {
exception[0]= jme;
}
}
};
try {
monitor.run(false, false, r);
} catch (InvocationTargetException e) {
JUnitPlugin.log(e);
} catch (InterruptedException e) {
JUnitPlugin.log(e);
}
if (exception[0] != null)
throw exception[0];
int flags= JavaElementLabelProvider.SHOW_DEFAULT;
ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaElementLabelProvider(flags));
dialog.setIgnoreCase(false);
dialog.setElements(packageList.toArray()); // XXX inefficient
return dialog;
}
/**
* Initializes TestRun Listener extensions
*/
private void loadTestRunListeners() {
testRunListeners= new Vector();
IExtensionPoint extensionPoint= Platform.getPluginRegistry().getExtensionPoint(ID_EXTENSION_POINT_TESTRUN_LISTENERS);
if (extensionPoint == null) {
return;
}
IConfigurationElement[] configs= extensionPoint.getConfigurationElements();
MultiStatus status= new MultiStatus(PLUGIN_ID, IStatus.OK, "Could not load some testRunner extension points", null); //$NON-NLS-1$
for (int i= 0; i < configs.length; i++) {
try {
ITestRunListener testRunListener= (ITestRunListener) configs[i].createExecutableExtension("class"); //$NON-NLS-1$
testRunListeners.add(testRunListener);
} catch (CoreException e) {
status.add(e.getStatus());
}
}
if (!status.isOK()) {
JUnitPlugin.log(status);
}
}
/**
* Returns an array of all TestRun listeners
*/
public Vector getTestRunListeners() {
if (testRunListeners == null) {
loadTestRunListeners();
}
return testRunListeners;
}
/**
* Adds a TestRun listener to the collection of listeners
*/
public void addTestRunListener(ITestRunListener newListener) {
if (testRunListeners == null) {
loadTestRunListeners();
}
testRunListeners.add(newListener);
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitPreferencePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Sebastian Davids: [email protected]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.junit.util.ExceptionHandler;
import org.eclipse.jdt.internal.junit.util.SWTUtil;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.ISharedImages;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ContentViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
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.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchViewerSorter;
/**
* Preference page for JUnit settings. Supports to define the failure
* stack filter patterns.
*/
public class JUnitPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String DEFAULT_NEW_FILTER_TEXT= ""; //$NON-NLS-1$
private static final Image IMG_CUNIT= JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_CLASS);
private static final Image IMG_PKG= JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_PACKAGE);
private static String[] fgDefaultFilterPatterns= new String[] { "org.eclipse.jdt.internal.junit.runner.*", //$NON-NLS-1$
"org.eclipse.jdt.internal.junit.ui.*", //$NON-NLS-1$
"junit.framework.TestCase", //$NON-NLS-1$
"junit.framework.TestResult", //$NON-NLS-1$
"junit.framework.TestSuite", //$NON-NLS-1$
"junit.framework.Assert", //$NON-NLS-1$
"java.lang.reflect.Method.invoke" //$NON-NLS-1$
};
// Step filter widgets
private CheckboxTableViewer fFilterViewer;
private Table fFilterTable;
private Button fShowOnErrorCheck;
private Button fAddPackageButton;
private Button fAddTypeButton;
private Button fRemoveFilterButton;
private Button fAddFilterButton;
private Button fEnableAllButton;
private Button fDisableAllButton;
private Text fEditorText;
private String fInvalidEditorText= null;
private TableEditor fTableEditor;
private TableItem fNewTableItem;
private Filter fNewStackFilter;
private Label fTableLabel;
private StackFilterContentProvider fStackFilterContentProvider;
/**
* Model object that represents a single entry in the filter table.
*/
private class Filter {
private String fName;
private boolean fChecked;
public Filter(String name, boolean checked) {
setName(name);
setChecked(checked);
}
public String getName() {
return fName;
}
public void setName(String name) {
fName= name;
}
public boolean isChecked() {
return fChecked;
}
public void setChecked(boolean checked) {
fChecked= checked;
}
public boolean equals(Object o) {
if (!(o instanceof Filter))
return false;
Filter other= (Filter) o;
return (getName().equals(other.getName()));
}
public int hashCode() {
return fName.hashCode();
}
}
/**
* Sorter for the filter table; sorts alphabetically ascending.
*/
private class FilterViewerSorter extends WorkbenchViewerSorter {
public int compare(Viewer viewer, Object e1, Object e2) {
ILabelProvider lprov= (ILabelProvider) ((ContentViewer) viewer).getLabelProvider();
String name1= lprov.getText(e1);
String name2= lprov.getText(e2);
if (name1 == null)
name1= ""; //$NON-NLS-1$
if (name2 == null)
name2= ""; //$NON-NLS-1$
if (name1.length() > 0 && name2.length() > 0) {
char char1= name1.charAt(name1.length() - 1);
char char2= name2.charAt(name2.length() - 1);
if (char1 == '*' && char1 != char2)
return -1;
if (char2 == '*' && char2 != char1)
return 1;
}
return name1.compareTo(name2);
}
}
/**
* Label provider for Filter model objects
*/
private class FilterLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object object, int column) {
return (column == 0) ? ((Filter) object).getName() : ""; //$NON-NLS-1$
}
public String getText(Object element) {
return ((Filter) element).getName();
}
public Image getColumnImage(Object object, int column) {
String name= ((Filter) object).getName();
if (name.endsWith(".*") || name.equals(JUnitMessages.getString("JUnitMainTab.label.defaultpackage"))) { //$NON-NLS-1$ //$NON-NLS-2$
//package
return IMG_PKG;
} else if ("".equals(name)) { //$NON-NLS-1$
//needed for the in-place editor
return null;
} else if ((Character.isUpperCase(name.charAt(0))) && (name.indexOf('.') < 0)) {
//class in default package
return IMG_CUNIT;
} else {
//fully-qualified class or other filter
final int lastDotIndex= name.lastIndexOf('.');
if ((-1 != lastDotIndex) && ((name.length() - 1) != lastDotIndex) && Character.isUpperCase(name.charAt(lastDotIndex + 1)))
return IMG_CUNIT;
}
//other filter
return null;
}
}
/**
* Content provider for the filter table. Content consists of instances of
* Filter.
*/
private class StackFilterContentProvider implements IStructuredContentProvider {
private List fFilters;
public StackFilterContentProvider() {
List active= createActiveStackFiltersList();
List inactive= createInactiveStackFiltersList();
populateFilters(active, inactive);
}
public void setDefaults() {
fFilterViewer.remove(fFilters.toArray());
List active= createDefaultStackFiltersList();
List inactive= new ArrayList();
populateFilters(active, inactive);
}
protected void populateFilters(List activeList, List inactiveList) {
fFilters= new ArrayList(activeList.size() + inactiveList.size());
populateList(activeList, true);
if (inactiveList.size() != 0)
populateList(inactiveList, false);
}
protected void populateList(List list, boolean checked) {
Iterator iterator= list.iterator();
while (iterator.hasNext()) {
String name= (String) iterator.next();
addFilter(name, checked);
}
}
public Filter addFilter(String name, boolean checked) {
Filter filter= new Filter(name, checked);
if (!fFilters.contains(filter)) {
fFilters.add(filter);
fFilterViewer.add(filter);
fFilterViewer.setChecked(filter, checked);
}
updateActions();
return filter;
}
public void saveFilters() {
List active= new ArrayList(fFilters.size());
List inactive= new ArrayList(fFilters.size());
Iterator iterator= fFilters.iterator();
while (iterator.hasNext()) {
Filter filter= (Filter) iterator.next();
String name= filter.getName();
if (filter.isChecked())
active.add(name);
else
inactive.add(name);
}
String pref= JUnitPreferencePage.serializeList((String[]) active.toArray(new String[active.size()]));
getPreferenceStore().setValue(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST, pref);
pref= JUnitPreferencePage.serializeList((String[]) inactive.toArray(new String[inactive.size()]));
getPreferenceStore().setValue(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST, pref);
}
public void removeFilters(Object[] filters) {
for (int i= (filters.length - 1); i >= 0; --i) {
Filter filter= (Filter) filters[i];
fFilters.remove(filter);
}
fFilterViewer.remove(filters);
updateActions();
}
public void toggleFilter(Filter filter) {
boolean newState= !filter.isChecked();
filter.setChecked(newState);
fFilterViewer.setChecked(filter, newState);
}
public Object[] getElements(Object inputElement) {
return fFilters.toArray();
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
public void dispose() {}
}
public JUnitPreferencePage() {
super();
setDescription(JUnitMessages.getString("JUnitPreferencePage.description")); //$NON-NLS-1$
setPreferenceStore(JUnitPlugin.getDefault().getPreferenceStore());
}
protected Control createContents(Composite parent) {
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.JUNIT_PREFERENCE_PAGE);
Composite composite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.numColumns= 1;
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
GridData data= new GridData();
data.verticalAlignment= GridData.FILL;
data.horizontalAlignment= GridData.FILL;
composite.setLayoutData(data);
createStackFilterPreferences(composite);
return composite;
}
/**
* Create a group to contain the step filter related widgetry
*/
private void createStackFilterPreferences(Composite composite) {
Composite container= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
container.setLayout(layout);
GridData gd= new GridData(GridData.FILL_BOTH);
container.setLayoutData(gd);
createShowCheck(container);
createFilterTable(container);
createStepFilterButtons(container);
}
private void createShowCheck(Composite composite) {
GridData data;
fShowOnErrorCheck= new Button(composite, SWT.CHECK);
fShowOnErrorCheck.setText(JUnitMessages.getString("JUnitPreferencePage.showcheck.label")); //$NON-NLS-1$
data= new GridData();
data.horizontalAlignment= GridData.FILL;
data.horizontalSpan= 2;
fShowOnErrorCheck.setLayoutData(data);
fShowOnErrorCheck.setSelection(getShowOnErrorOnly());
}
private void createFilterTable(Composite container) {
fTableLabel= new Label(container, SWT.NONE);
fTableLabel.setText(JUnitMessages.getString("JUnitPreferencePage.filter.label")); //$NON-NLS-1$
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalSpan= 2;
fTableLabel.setLayoutData(gd);
fFilterTable= new Table(container, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
gd= new GridData(GridData.FILL_HORIZONTAL);
fFilterTable.setLayoutData(gd);
TableLayout tableLayout= new TableLayout();
ColumnLayoutData[] columnLayoutData= new ColumnLayoutData[1];
columnLayoutData[0]= new ColumnWeightData(100);
tableLayout.addColumnData(columnLayoutData[0]);
fFilterTable.setLayout(tableLayout);
new TableColumn(fFilterTable, SWT.NONE);
fFilterViewer= new CheckboxTableViewer(fFilterTable);
fTableEditor= new TableEditor(fFilterTable);
fFilterViewer.setLabelProvider(new FilterLabelProvider());
fFilterViewer.setSorter(new FilterViewerSorter());
fStackFilterContentProvider= new StackFilterContentProvider();
fFilterViewer.setContentProvider(fStackFilterContentProvider);
// input just needs to be non-null
fFilterViewer.setInput(this);
gd= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fFilterViewer.getTable().setLayoutData(gd);
fFilterViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
Filter filter= (Filter) event.getElement();
fStackFilterContentProvider.toggleFilter(filter);
}
});
fFilterViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection= event.getSelection();
fRemoveFilterButton.setEnabled(!selection.isEmpty());
}
});
}
private void createStepFilterButtons(Composite container) {
Composite buttonContainer= new Composite(container, SWT.NONE);
GridData gd= new GridData(GridData.FILL_VERTICAL);
buttonContainer.setLayoutData(gd);
GridLayout buttonLayout= new GridLayout();
buttonLayout.numColumns= 1;
buttonLayout.marginHeight= 0;
buttonLayout.marginWidth= 0;
buttonContainer.setLayout(buttonLayout);
fAddFilterButton= new Button(buttonContainer, SWT.PUSH);
fAddFilterButton.setText(JUnitMessages.getString("JUnitPreferencePage.addfilterbutton.label")); //$NON-NLS-1$
fAddFilterButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addfilterbutton.tooltip")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
fAddFilterButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fAddFilterButton);
fAddFilterButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
editFilter();
}
});
fAddTypeButton= new Button(buttonContainer, SWT.PUSH);
fAddTypeButton.setText(JUnitMessages.getString("JUnitPreferencePage.addtypebutton.label")); //$NON-NLS-1$
fAddTypeButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addtypebutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fAddTypeButton);
fAddTypeButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fAddTypeButton);
fAddTypeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
addType();
}
});
fAddPackageButton= new Button(buttonContainer, SWT.PUSH);
fAddPackageButton.setText(JUnitMessages.getString("JUnitPreferencePage.addpackagebutton.label")); //$NON-NLS-1$
fAddPackageButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addpackagebutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fAddPackageButton);
fAddPackageButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fAddPackageButton);
fAddPackageButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
addPackage();
}
});
fRemoveFilterButton= new Button(buttonContainer, SWT.PUSH);
fRemoveFilterButton.setText(JUnitMessages.getString("JUnitPreferencePage.removefilterbutton.label")); //$NON-NLS-1$
fRemoveFilterButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.removefilterbutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fRemoveFilterButton);
fRemoveFilterButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fRemoveFilterButton);
fRemoveFilterButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
removeFilters();
}
});
fRemoveFilterButton.setEnabled(false);
fEnableAllButton= new Button(buttonContainer, SWT.PUSH);
fEnableAllButton.setText(JUnitMessages.getString("JUnitPreferencePage.enableallbutton.label")); //$NON-NLS-1$
fEnableAllButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.enableallbutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fEnableAllButton);
fEnableAllButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fEnableAllButton);
fEnableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
checkAllFilters(true);
}
});
fDisableAllButton= new Button(buttonContainer, SWT.PUSH);
fDisableAllButton.setText(JUnitMessages.getString("JUnitPreferencePage.disableallbutton.label")); //$NON-NLS-1$
fDisableAllButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.disableallbutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fDisableAllButton);
fDisableAllButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fDisableAllButton);
fDisableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
checkAllFilters(false);
}
});
}
private GridData getButtonGridData(Button button) {
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
int widthHint= convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
gd.widthHint= Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
gd.heightHint= convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT);
return gd;
}
public void init(IWorkbench workbench) {}
/**
* Create a new filter in the table (with the default 'new filter' value),
* then open up an in-place editor on it.
*/
private void editFilter() {
// if a previous edit is still in progress, finish it
if (fEditorText != null)
validateChangeAndCleanup();
fNewStackFilter= fStackFilterContentProvider.addFilter(DEFAULT_NEW_FILTER_TEXT, true);
fNewTableItem= fFilterTable.getItem(0);
// create & configure Text widget for editor
// Fix for bug 1766. Border behavior on for text fields varies per platform.
// On Motif, you always get a border, on other platforms,
// you don't. Specifying a border on Motif results in the characters
// getting pushed down so that only there very tops are visible. Thus,
// we have to specify different style constants for the different platforms.
int textStyles= SWT.SINGLE | SWT.LEFT;
if (!SWT.getPlatform().equals("motif")) //$NON-NLS-1$
textStyles |= SWT.BORDER;
fEditorText= new Text(fFilterTable, textStyles);
GridData gd= new GridData(GridData.FILL_BOTH);
fEditorText.setLayoutData(gd);
// set the editor
fTableEditor.horizontalAlignment= SWT.LEFT;
fTableEditor.grabHorizontal= true;
fTableEditor.setEditor(fEditorText, fNewTableItem, 0);
// get the editor ready to use
fEditorText.setText(fNewStackFilter.getName());
fEditorText.selectAll();
setEditorListeners(fEditorText);
fEditorText.setFocus();
}
private void setEditorListeners(Text text) {
// CR means commit the changes, ESC means abort and don't commit
text.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if (event.character == SWT.CR) {
if (fInvalidEditorText != null) {
fEditorText.setText(fInvalidEditorText);
fInvalidEditorText= null;
} else
validateChangeAndCleanup();
} else if (event.character == SWT.ESC) {
removeNewFilter();
cleanupEditor();
}
}
});
// Consider loss of focus on the editor to mean the same as CR
text.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent event) {
if (fInvalidEditorText != null) {
fEditorText.setText(fInvalidEditorText);
fInvalidEditorText= null;
} else
validateChangeAndCleanup();
}
});
// Consume traversal events from the text widget so that CR doesn't
// traverse away to dialog's default button. Without this, hitting
// CR in the text field closes the entire dialog.
text.addListener(SWT.Traverse, new Listener() {
public void handleEvent(Event event) {
event.doit= false;
}
});
}
private void validateChangeAndCleanup() {
String trimmedValue= fEditorText.getText().trim();
// if the new value is blank, remove the filter
if (trimmedValue.length() < 1)
removeNewFilter();
// if it's invalid, beep and leave sitting in the editor
else if (!validateEditorInput(trimmedValue)) {
fInvalidEditorText= trimmedValue;
fEditorText.setText(JUnitMessages.getString("JUnitPreferencePage.invalidstepfilterreturnescape")); //$NON-NLS-1$
getShell().getDisplay().beep();
return;
// otherwise, commit the new value if not a duplicate
} else {
Object[] filters= fStackFilterContentProvider.getElements(null);
for (int i= 0; i < filters.length; i++) {
Filter filter= (Filter) filters[i];
if (filter.getName().equals(trimmedValue)) {
removeNewFilter();
cleanupEditor();
return;
}
}
fNewTableItem.setText(trimmedValue);
fNewStackFilter.setName(trimmedValue);
fFilterViewer.refresh();
}
cleanupEditor();
}
/**
* Cleanup all widgetry & resources used by the in-place editing
*/
private void cleanupEditor() {
if (fEditorText == null)
return;
fNewStackFilter= null;
fNewTableItem= null;
fTableEditor.setEditor(null, null, 0);
fEditorText.dispose();
fEditorText= null;
}
private void removeNewFilter() {
fStackFilterContentProvider.removeFilters(new Object[] { fNewStackFilter });
}
/**
* A valid step filter is simply one that is a valid Java identifier.
* and, as defined in the JDI spec, the regular expressions used for
* step filtering must be limited to exact matches or patterns that
* begin with '*' or end with '*'. Beyond this, a string cannot be validated
* as corresponding to an existing type or package (and this is probably not
* even desirable).
*/
private boolean validateEditorInput(String trimmedValue) {
char firstChar= trimmedValue.charAt(0);
if ((!(Character.isJavaIdentifierStart(firstChar)) || (firstChar == '*')))
return false;
int length= trimmedValue.length();
for (int i= 1; i < length; i++) {
char c= trimmedValue.charAt(i);
if (!Character.isJavaIdentifierPart(c)) {
if (c == '.' && i != (length - 1))
continue;
if (c == '*' && i == (length - 1))
continue;
return false;
}
}
return true;
}
private void addType() {
Shell shell= getShell();
SelectionDialog dialog= null;
try {
dialog=
JavaUI.createTypeDialog(
shell,
new ProgressMonitorDialog(shell),
SearchEngine.createWorkspaceScope(),
IJavaElementSearchConstants.CONSIDER_CLASSES,
false);
} catch (JavaModelException jme) {
String title= JUnitMessages.getString("JUnitPreferencePage.addtypedialog.title"); //$NON-NLS-1$
String message= JUnitMessages.getString("JUnitPreferencePage.addtypedialog.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(jme, shell, title, message);
return;
}
dialog.setTitle(JUnitMessages.getString("JUnitPreferencePage.addtypedialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitPreferencePage.addtypedialog.message")); //$NON-NLS-1$
if (dialog.open() == IDialogConstants.CANCEL_ID)
return;
Object[] types= dialog.getResult();
if (types != null && types.length > 0) {
IType type= (IType) types[0];
fStackFilterContentProvider.addFilter(type.getFullyQualifiedName(), true);
}
}
private void addPackage() {
Shell shell= getShell();
ElementListSelectionDialog dialog= null;
try {
dialog= JUnitPlugin.createAllPackagesDialog(shell, null, true);
} catch (JavaModelException jme) {
String title= JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.title"); //$NON-NLS-1$
String message= JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(jme, shell, title, message);
return;
}
dialog.setTitle(JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.message")); //$NON-NLS-1$
dialog.setMultipleSelection(true);
if (dialog.open() == IDialogConstants.CANCEL_ID)
return;
Object[] packages= dialog.getResult();
if (packages == null)
return;
for (int i= 0; i < packages.length; i++) {
IJavaElement pkg= (IJavaElement) packages[i];
String filter= pkg.getElementName();
if (filter.length() < 1)
filter= JUnitMessages.getString("JUnitMainTab.label.defaultpackage"); //$NON-NLS-1$
else
filter += ".*"; //$NON-NLS-1$
fStackFilterContentProvider.addFilter(filter, true);
}
}
private void removeFilters() {
IStructuredSelection selection= (IStructuredSelection) fFilterViewer.getSelection();
fStackFilterContentProvider.removeFilters(selection.toArray());
}
private void checkAllFilters(boolean check) {
Object[] filters= fStackFilterContentProvider.getElements(null);
for (int i= (filters.length - 1); i >= 0; --i)
((Filter) filters[i]).setChecked(check);
fFilterViewer.setAllChecked(check);
}
public boolean performOk() {
IPreferenceStore store= getPreferenceStore();
store.setValue(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY, fShowOnErrorCheck.getSelection());
fStackFilterContentProvider.saveFilters();
return true;
}
protected void performDefaults() {
setDefaultValues();
super.performDefaults();
}
private void setDefaultValues() {
fStackFilterContentProvider.setDefaults();
}
/**
* Returns the default list of active stack filters.
*
* @return list
*/
protected List createDefaultStackFiltersList() {
return Arrays.asList(fgDefaultFilterPatterns);
}
/**
* Returns a list of active stack filters.
*
* @return list
*/
protected List createActiveStackFiltersList() {
return Arrays.asList(getFilterPatterns());
}
/**
* Returns a list of active stack filters.
*
* @return list
*/
protected List createInactiveStackFiltersList() {
String[] strings=
JUnitPreferencePage.parseList(getPreferenceStore().getString(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST));
return Arrays.asList(strings);
}
protected void updateActions() {
if (fEnableAllButton == null)
return;
boolean enabled= fFilterViewer.getTable().getItemCount() > 0;
fEnableAllButton.setEnabled(enabled);
fDisableAllButton.setEnabled(enabled);
}
public static String[] getFilterPatterns() {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
return JUnitPreferencePage.parseList(store.getString(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST));
}
public static boolean getFilterStack() {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
return store.getBoolean(IJUnitPreferencesConstants.DO_FILTER_STACK);
}
public static void setFilterStack(boolean filter) {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
store.setValue(IJUnitPreferencesConstants.DO_FILTER_STACK, filter);
}
public static void initializeDefaults(IPreferenceStore store) {
store.setDefault(IJUnitPreferencesConstants.DO_FILTER_STACK, true);
store.setDefault(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY, false);
String list= store.getString(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST);
if ("".equals(list)) { //$NON-NLS-1$
String pref= JUnitPreferencePage.serializeList(fgDefaultFilterPatterns);
store.setValue(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST, pref);
}
store.setValue(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST, ""); //$NON-NLS-1$
}
public static boolean getShowOnErrorOnly() {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
return store.getBoolean(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY);
}
/**
* Parses the comma separated string into an array of strings
*
* @return list
*/
private static String[] parseList(String listString) {
List list= new ArrayList(10);
StringTokenizer tokenizer= new StringTokenizer(listString, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens())
list.add(tokenizer.nextToken());
return (String[]) list.toArray(new String[list.size()]);
}
/**
* Serializes the array of strings into one comma
* separated string.
*
* @param list array of strings
* @return a single string composed of the given list
*/
private static String serializeList(String[] list) {
if (list == null)
return ""; //$NON-NLS-1$
StringBuffer buffer= new StringBuffer();
for (int i= 0; i < list.length; i++) {
if (i > 0)
buffer.append(',');
buffer.append(list[i]);
}
return buffer.toString();
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/OpenEditorAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
/**
* Abstract Action for opening a Java editor.
*/
public abstract class OpenEditorAction extends Action {
protected String fClassName;
protected TestRunnerViewPart fTestRunner;
/**
* Constructor for OpenEditorAction.
*/
protected OpenEditorAction(TestRunnerViewPart testRunner, String testClassName) {
super(JUnitMessages.getString("OpenEditorAction.action.label")); //$NON-NLS-1$
fClassName= testClassName;
fTestRunner= testRunner;
}
/*
* @see IAction#run()
*/
public void run() {
ITextEditor textEditor= null;
try {
IJavaElement element= findElement(fTestRunner.getLaunchedProject(), fClassName);
if (element == null) {
MessageDialog.openError(fTestRunner.getSite().getShell(),
JUnitMessages.getString("OpenEditorAction.error.cannotopen.title"), JUnitMessages.getString("OpenEditorAction.error.cannotopen.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
// use of internal API for backward compatibility with 1.0
textEditor= (ITextEditor)EditorUtility.openInEditor(element, false);
} catch (CoreException e) {
ErrorDialog.openError(fTestRunner.getSite().getShell(), JUnitMessages.getString("OpenEditorAction.error.dialog.title"), JUnitMessages.getString("OpenEditorAction.error.dialog.message"), e.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
if (textEditor == null) {
fTestRunner.postInfo(JUnitMessages.getString("OpenEditorAction.message.cannotopen")); //$NON-NLS-1$
return;
}
reveal(textEditor);
}
protected abstract IJavaElement findElement(IJavaProject project, String className) throws JavaModelException;
protected abstract void reveal(ITextEditor editor);
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/OpenEditorAtLineAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
/**
* Open a test in the Java editor and reveal a given line
*/
public class OpenEditorAtLineAction extends OpenEditorAction {
private int fLineNumber;
/**
* Constructor for OpenEditorAtLineAction.
*/
public OpenEditorAtLineAction(TestRunnerViewPart testRunner, String className, int line) {
super(testRunner, className);
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.OPENEDITORATLINE_ACTION);
fLineNumber= line;
}
protected void reveal(ITextEditor textEditor) {
if (fLineNumber >= 0) {
try {
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
textEditor.selectAndReveal(document.getLineOffset(fLineNumber-1), document.getLineLength(fLineNumber-1));
} catch (BadLocationException x) {
// marker refers to invalid text position -> do nothing
}
}
}
protected IJavaElement findElement(IJavaProject project, String className) throws JavaModelException {
return project.findType(className);
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/OpenTestAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
/**
* Open a class on a Test method.
*/
public class OpenTestAction extends OpenEditorAction {
private String fMethodName;
private ISourceRange fRange;
/**
* Constructor for OpenTestAction.
*/
public OpenTestAction(TestRunnerViewPart testRunner, String className, String method) {
super(testRunner, className);
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.OPENTEST_ACTION);
fMethodName= method;
}
public OpenTestAction(TestRunnerViewPart testRunner, String className) {
this(testRunner, className, null);
}
protected IJavaElement findElement(IJavaProject project, String className) throws JavaModelException {
IType type= project.findType(className);
if (type == null)
return null;
if (fMethodName == null)
return type;
IMethod method= findMethod(type);
if (method == null) {
ITypeHierarchy typeHierarchy= type.newSupertypeHierarchy(null);
IType[] types= typeHierarchy.getAllSuperclasses(type);
for (int i= 0; i < types.length; i++) {
method= findMethod(types[i]);
if (method != null)
break;
}
}
if (method != null)
fRange= method.getNameRange();
return method;
}
IMethod findMethod(IType type) throws JavaModelException {
IMethod method= type.getMethod(fMethodName, new String[0]);
if (method != null && method.exists())
return method;
return null;
}
protected void reveal(ITextEditor textEditor) {
if (fRange != null)
textEditor.selectAndReveal(fRange.getOffset(), fRange.getLength());
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunInfo.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
/**
* Store information about an executed test.
*/
public class TestRunInfo extends Object {
public String fTestId;
public String fTestName;
public String fTrace;
public int fStatus;
public TestRunInfo(String testId, String testName){
fTestName= testName;
fTestId= testId;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fTestId.hashCode();
}
/*
* @see Object#equals(Object)
*/
public boolean equals(Object obj) {
return fTestId.equals(obj);
}
}
|
33,234 |
Bug 33234 Goto source doesn't work when running a single test [JUnit]
|
RC 1 - JUnit setup - select VectorTest.testCapacity - run->JUnit Test - in JUnit view part go to hierarchy - select testCapacity - activate Goto File from context menu Observe: you get an error dialog saying that the test class can't be found.
|
resolved fixed
|
1ba9033
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:30:58Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener2, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrors;
/**
* Number of failures during this test run
*/
protected int fFailures;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private TestRunInfo fFirstFailure;
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch= null;
/**
* Actions
*/
private Action fRerunLastTestAction;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
Image fOriginalViewImage= null;
IElementChangedListener fDirtyListener= null;
private class StopAction extends Action{
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action{
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrors), String.valueOf(fFailures)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFirstFailure != null) {
fActiveRunView.setSelectedTest(fFirstFailure.fTestId);
handleTestSelected(fFirstFailure.fTestId);
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrors+fFailures > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null)
fTestInfos.put(testId, new TestRunInfo(testId, testName));
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.fTrace= trace;
testInfo.fStatus= status;
if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
else
fFailures++;
if (fFirstFailure == null)
fFirstFailure= testInfo;
// show the view on the first error only
if (fShowOnErrorOnly && (fErrors + fFailures == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.fTrace == null || !info.fTrace.equals(trace)) {
info.fTrace= trace;
showFailure(info.fTrace);
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.fStatus)
return;
if (info.fStatus == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailures++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
} else if (info.fStatus == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrors--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrors--;
fFailures++;
}
} else if (info.fStatus == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailures--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailures--;
fErrors++;
}
}
info.fStatus= status;
final TestRunInfo finalInfo= info;
postAsyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
Vector listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.copyInto(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
getSite().getKeyBindingService().unregisterAction(fRerunLastTestAction);
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void postAsyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailures+fErrors);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrors, fFailures);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrors);
fCounterPanel.setFailureValue(fFailures);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrors+fFailures> 0);
}
protected void postShowTestResultsView() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
SashForm sashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(sashForm, SWT.NONE);
CTabFolder tabFolder= createTestRunViews(top);
tabFolder.setLayoutData(new TabFolderLayout());
top.setContent(tabFolder);
ViewForm bottom= new ViewForm(sashForm, SWT.NONE);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, this);
bottom.setContent(fFailureView.getComposite());
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
// fill the failure trace viewer toolbar
ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar);
failureToolBarmanager.add(new EnableStackFilterAction(fFailureView));
failureToolBarmanager.update(true);
sashForm.setWeights(new int[]{50, 50});
return sashForm;
}
private void reset(final int testCount) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailures= 0;
fErrors= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFirstFailure= null;
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
parent.setLayout(gridLayout);
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fRerunLastTestAction= new RerunLastAction();
fRerunLastTestAction.setActionDefinitionId("org.eclipse.jdt.junit.reruntest"); //$NON-NLS-1$
toolBar.add(new StopAction());
toolBar.add(fRerunLastTestAction);
actionBars.updateActionBars();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
actionBars.setGlobalActionHandler(
IWorkbenchActionConstants.COPY,
new CopyTraceAction(fFailureView));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
getSite().getKeyBindingService().registerAction(fRerunLastTestAction);
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(""); //$NON-NLS-1$
} else {
showFailure(testInfo.fTrace);
}
}
private void showFailure(final String failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
}
|
33,552 |
Bug 33552 Show in>Package Explore not consistent with Show in Package Explorer
|
1) Show in>PackageExplorer selects the editor input 2) "Show in Package Explorer" selects the method. we should do 2) it reduces tree expansions, and enables the user to quickly initiate an operation on the editor input.
|
resolved fixed
|
b966dfa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:33:34Z | 2003-02-28T16:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ShowInPackageViewAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IElementComparer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart;
/**
* This action reveals the currently selected Java element in the
* package explorer.
* <p>
* The action is applicable to selections containing elements of type
* <code>IJavaElement</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
* @since 2.0
*/
public class ShowInPackageViewAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/**
* Creates a new <code>ShowInPackageViewAction</code>. The action requires
* that the selection provided by the site's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public ShowInPackageViewAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("ShowInPackageViewAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("ShowInPackageViewAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("ShowInPackageViewAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.SHOW_IN_PACKAGEVIEW_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public ShowInPackageViewAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.canOperateOn(fEditor));
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(checkEnabled(selection));
}
private boolean checkEnabled(IStructuredSelection selection) {
if (selection.size() != 1)
return false;
return selection.getFirstElement() instanceof IJavaElement;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
try {
IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
if (element != null)
run(element);
} catch (JavaModelException e) {
JavaPlugin.log(e);
String message= ActionMessages.getString("ShowInPackageViewAction.error.message"); //$NON-NLS-1$
ErrorDialog.openError(getShell(), getDialogTitle(), message, e.getStatus());
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
if (!checkEnabled(selection))
return;
run((IJavaElement)selection.getFirstElement());
}
private void run(IJavaElement element) {
if (element == null)
return;
PackageExplorerPart view= PackageExplorerPart.openInActivePerspective();
if (view != null) {
if (reveal(view, element))
return;
element= getVisibleParent(element);
if (element != null) {
if (reveal(view, element))
return;
IResource resource= element.getResource();
if (resource != null) {
if (reveal(view, resource))
return;
}
}
MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("ShowInPackageViewAction.not_found")); //$NON-NLS-1$
}
}
private boolean reveal(PackageExplorerPart view, Object element) {
if (element == null)
return false;
view.selectReveal(new StructuredSelection(element));
IElementComparer comparer= view.getTreeViewer().getComparer();
Object selected= getSelectedElement(view);
if (comparer != null ? comparer.equals(element, selected) : element.equals(selected))
return true;
return false;
}
private Object getSelectedElement(PackageExplorerPart view) {
return ((IStructuredSelection)view.getSite().getSelectionProvider().getSelection()).getFirstElement();
}
private IJavaElement getVisibleParent(IJavaElement element) {
// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19104
if (element == null)
return null;
switch (element.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
element= (IJavaElement)element.getOpenable();
break;
case IJavaElement.JAVA_MODEL:
element= null;
break;
}
if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
ICompilationUnit unit= (ICompilationUnit)element;
if (unit.isWorkingCopy())
element= unit.getOriginalElement();
}
return element;
}
private static String getDialogTitle() {
return ActionMessages.getString("ShowInPackageViewAction.dialog.title"); //$NON-NLS-1$
}
}
|
33,221 |
Bug 33221 Java Working Set and synthetic library containers
|
RC1 - create Java working set just containing the source folder "compare" of the Compare plugin - use this working set to filter Package Explorer Observe: the synthetic library container is visible, but empty
|
resolved fixed
|
bf1d6cc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T19:45:23Z | 2003-02-26T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetFilter.java
| |
33,040 |
Bug 33040 No single Undo for generate delegate methods
|
RC 1 - JUnit setup - open TestCase - select fName - generate delegate methods for all String methods - press Ctrl+Z Observe: only one method is removed.
|
resolved fixed
|
e41dc64
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T22:55:44Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddDelegateMethodsAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Martin Moebius
* *****************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.eclipse.core.resources.IWorkspaceRunnable;
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.swt.graphics.Image;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
/**
* Creates delegate methods for a type's fields. Opens a dialog with a list of
* fields for which delegate methods can be generated. User is able to check or
* uncheck items before methods are generated.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IField</code> or <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* Contributors:
* Sebastian Davids: [email protected] - bug: 28793
* @since 2.1
*/
public class AddDelegateMethodsAction extends SelectionDispatchAction {
private static boolean fgReplaceFlag = false;
private static boolean fgOverrideFinalsFlag = false;
private static final String DIALOG_TITLE = ActionMessages.getString("AddDelegateMethodsAction.error.title"); //$NON-NLS-1$
private CompilationUnitEditor fEditor;
/**
* Creates a new <code>AddDelegateMethodsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public AddDelegateMethodsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddDelegateMethodsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddDelegateMethodsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddDelegateMethodsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_DELEGATE_METHODS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddDelegateMethodsAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor = editor;
setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
try {
IField[] selectedFields = getSelectedFields(selection);
if (canEnableOn(selectedFields)) {
run(selectedFields[0].getDeclaringType(), selectedFields, false);
return;
}
Object firstElement = selection.getFirstElement();
if (firstElement instanceof IType)
run((IType) firstElement, new IField[0], false);
else if (firstElement instanceof ICompilationUnit)
run(JavaElementUtil.getMainType((ICompilationUnit) firstElement), new IField[0], false);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
if (canEnableOn(getSelectedFields(selection)))
return true;
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType))
return canEnableOn((IType) selection.getFirstElement());
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return canEnableOn(JavaElementUtil.getMainType((ICompilationUnit) selection.getFirstElement()));
return false;
}
private static boolean canEnableOn(IType type) throws JavaModelException {
if (type == null || type.getCompilationUnit() == null)
return false;
return canEnableOn(type.getFields());
}
private static boolean canEnableOn(IField[] fields) throws JavaModelException {
if (fields == null) {
return false;
}
int count = 0;
for (int i = 0; i < fields.length; i++) {
if (!hasPrimitiveType(fields[i]) || isArray(fields[i])) {
count++;
}
}
return (count > 0);
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements = selection.toList();
int nElements = elements.size();
if (nElements > 0) {
IField[] res = new IField[nElements];
ICompilationUnit cu = null;
for (int i = 0; i < nElements; i++) {
Object curr = elements.get(i);
if (curr instanceof IField) {
IField fld = (IField) curr;
if (i == 0) {
// remember the cu of the first element
cu = fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no delegates for fields in interfaces or fields with
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i] = fld;
} else {
return null;
}
}
return res;
}
return null;
}
private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
if (!ElementValidator.check(type, getShell(), DIALOG_TITLE, editor))
return;
if (!ActionUtil.isProcessable(getShell(), type))
return;
if(!canEnableOn(type)){
MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.not_applicable")); //$NON-NLS-1$
return;
}
showUI(type, preselected);
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
try {
IJavaElement input= SelectionConverter.getInput(fEditor);
if (!ActionUtil.isProcessable(getShell(), input))
return;
IJavaElement[] elements = SelectionConverter.codeResolve(fEditor);
if (elements.length == 1 && (elements[0] instanceof IField)) {
IField field = (IField) elements[0];
run(field.getDeclaringType(), new IField[] { field }, true);
return;
}
IJavaElement element = SelectionConverter.getElementAtOffset(fEditor);
if (element != null) {
IType type = (IType) element.getAncestor(IJavaElement.TYPE);
if (type != null) {
if (type.getFields().length > 0) {
run(type, new IField[0], true);
return;
}
}
}
MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.not_applicable")); //$NON-NLS-1$
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
}
}
//---- Helpers -------------------------------------------------------------------
/**build ui */
private void showUI(IType type, IField[] preselected) {
try {
FieldContentProvider provider = new FieldContentProvider(type);
Methods2FieldLabelProvider methodLabel = new Methods2FieldLabelProvider();
CheckedTreeSelectionDialog dialog = new CheckedTreeSelectionDialog(getShell(), methodLabel, provider);
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection) {
StatusInfo state = new StatusInfo();
if (selection != null && selection.length > 0) {
HashSet map = new HashSet(selection.length);
int count = 0;
for (int i = 0; i < selection.length; i++) {
Object key = selection[i];
if (selection[i] instanceof Methods2Field) {
count++;
try {
key = createSignatureKey(((Methods2Field) selection[i]).fMethod);
} catch (JavaModelException e) {
return new StatusInfo(StatusInfo.ERROR, e.toString());
}
}
if (!map.add(key)) { //$NON-NLS-1$
state = new StatusInfo(IStatus.ERROR, ActionMessages.getString("AddDelegateMethodsAction.duplicate_methods")); //$NON-NLS-1$
break;
} else {
String message;
if (count == 1) {
message = ActionMessages.getFormattedString("AddDelegateMethodsAction.selectioninfo.one", String.valueOf(count)); //$NON-NLS-1$
} else {
message = ActionMessages.getFormattedString("AddDelegateMethodsAction.selectioninfo.more", String.valueOf(count)); //$NON-NLS-1$
}
state = new StatusInfo(IStatus.INFO, message);
}
}
}
return state;
}
});
dialog.setSorter(new Methods2FieldSorter());
dialog.setInput(provider);
dialog.setContainerMode(true);
dialog.setMessage(ActionMessages.getString("AddDelegateMethodsAction.message")); //$NON-NLS-1$
dialog.setTitle(ActionMessages.getString("AddDelegateMethodsAction.title")); //$NON-NLS-1$
dialog.setExpandedElements(preselected);
int result = dialog.open();
if (result == Window.OK) {
Object[] o = dialog.getResult();
if (o == null)
return;
ArrayList methods = new ArrayList(o.length);
for (int i = 0; i < o.length; i++) {
if (o[i] instanceof Methods2Field)
methods.add(o[i]);
}
IEditorPart part = EditorUtility.openInEditor(type);
type = (IType) JavaModelUtil.toWorkingCopy(type);
IMethod[] createdMethods = processResults(methods, type);
if (createdMethods != null && createdMethods.length > 0) {
EditorUtility.revealInEditor(part, createdMethods[0]);
}
}
} catch (CoreException e) {
ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
}
}
/**Runnable for the operation*/
private static class ResultRunner implements IWorkspaceRunnable {
/**List with Methods2Field*/
List fList = null;
/**Type to add methods to*/
IType fType = null;
List fCreatedMethods;
public ResultRunner(List resultList, IType type) {
fList = resultList;
fType = type;
fCreatedMethods = new ArrayList();
}
public IMethod[] getCreatedMethods() {
return (IMethod[]) fCreatedMethods.toArray(new IMethod[fCreatedMethods.size()]);
}
public void run(IProgressMonitor monitor) throws CoreException {
String message = ActionMessages.getFormattedString("AddDelegateMethodsAction.monitor.message", String.valueOf(fList.size())); //$NON-NLS-1$
monitor.beginTask(message, fList.size());
// the preferences
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings();
boolean addComments = settings.createComments;
// already existing methods
IMethod[] existingMethods = fType.getMethods();
//the delemiter used
String lineDelim = StubUtility.getLineDelimiterUsed(fType);
// the indent used + 1
int indent = StubUtility.getIndentUsed(fType) + 1;
// perhaps we have to add import statements
final ImportsStructure imports =
new ImportsStructure(fType.getCompilationUnit(), settings.importOrder, settings.importThreshold, true);
for (int i = 0; i < fList.size(); i++) {
//long time=System.currentTimeMillis();
//check for cancel each iteration
if (monitor.isCanceled()) {
if (i > 0) {
imports.create(false, null);
}
return;
}
ITypeHierarchy typeHierarchy = fType.newSupertypeHierarchy(null);
String content = null;
Methods2Field wrapper = (Methods2Field) fList.get(i);
IMethod curr = wrapper.fMethod;
IField field = wrapper.fField;
IMethod overwrittenMethod =
JavaModelUtil.findMethodImplementationInHierarchy(
typeHierarchy,
fType,
curr.getElementName(),
curr.getParameterTypes(),
curr.isConstructor());
if (overwrittenMethod == null) {
content = createStub(field, curr, addComments, overwrittenMethod, imports);
} else {
int flags = overwrittenMethod.getFlags();
if (Flags.isFinal(flags) || Flags.isPrivate(flags)) {
// we could ask before overwriting final methods
if (fgOverrideFinalsFlag) {
System.out.println("method final"); //$NON-NLS-1$
System.out.println(overwrittenMethod);
}
}
IMethod declaration =
JavaModelUtil.findMethodDeclarationInHierarchy(
typeHierarchy,
fType,
curr.getElementName(),
curr.getParameterTypes(),
curr.isConstructor());
content = createStub(field, declaration, addComments, overwrittenMethod, imports);
}
IJavaElement sibling = null;
IMethod existing =
JavaModelUtil.findMethod(
curr.getElementName(),
curr.getParameterTypes(),
curr.isConstructor(),
existingMethods);
if (existing != null) {
// we could ask before replacing a method
if (fgReplaceFlag) {
System.out.println("method does already exists"); //$NON-NLS-1$
System.out.println(existing);
sibling = StubUtility.findNextSibling(existing);
existing.delete(false, null);
} else {
continue;
}
} else if (curr.isConstructor() && existingMethods.length > 0) {
// add constructors at the beginning
sibling = existingMethods[0];
}
String formattedContent = StubUtility.codeFormat(content, indent, lineDelim) + lineDelim;
IMethod created = fType.createMethod(formattedContent, sibling, true, null);
fCreatedMethods.add(created);
monitor.worked(1);
//System.out.println(System.currentTimeMillis()-time +" for #"+i);
}
imports.create(false, null);
}
private String createStub(
IField field,
IMethod curr,
boolean addComment,
IMethod overridden,
IImportsStructure imports)
throws CoreException {
String methodName = curr.getElementName();
String[] paramNames = curr.getParameterNames();
String returnTypSig = curr.getReturnType();
StringBuffer buf = new StringBuffer();
if (addComment) {
String comment =
StubUtility.getMethodComment(
fType.getCompilationUnit(),
fType.getElementName(),
methodName,
paramNames,
curr.getExceptionTypes(),
returnTypSig,
overridden);
if (comment != null) {
buf.append(comment);
}
}
String methodDeclaration = null;
if (fType.isClass()) {
StringBuffer body = new StringBuffer();
if (!Signature.SIG_VOID.equals(returnTypSig)) {
body.append("return "); //$NON-NLS-1$
}
if (JdtFlags.isStatic(curr)) {
body.append(resolveTypeOfField(field).getElementName());
} else {
body.append(field.getElementName());
}
body.append('.').append(methodName).append('(');
for (int i = 0; i < paramNames.length; i++) {
body.append(paramNames[i]);
if (i < paramNames.length - 1)
body.append(',');
}
body.append(");"); //$NON-NLS-1$
methodDeclaration = body.toString();
}
StubUtility.genMethodDeclaration(fType.getElementName(), curr, methodDeclaration, imports, buf);
return buf.toString();
}
}
/**creates methods in class*/
private IMethod[] processResults(List list, IType type) throws InvocationTargetException {
if (list.size() == 0)
return null;
ResultRunner resultRunner = new ResultRunner(list, type);
IRunnableContext runnableContext = new ProgressMonitorDialog(getShell());
try {
runnableContext.run(false, true, new WorkbenchRunnableAdapter(resultRunner));
} catch (InterruptedException e) {
// cancel pressed
return null;
}
return resultRunner.getCreatedMethods();
}
/** The model (content provider) for the field-methods tree */
private static class FieldContentProvider implements ITreeContentProvider {
private Map fTreeMap = null;
private Map fFieldMap = null;
private Map fFilter = null;
/**
* Method FieldContentProvider.
* @param type outer type to insert in (hide final methods in tree))
*/
FieldContentProvider(IType type) throws JavaModelException {
//hiding final methods
fFilter = new HashMap();
//mapping name to methods
fTreeMap = new TreeMap();
//mapping name to field
fFieldMap = new HashMap();
buildModel(type);
}
private void buildModel(IType type) throws JavaModelException {
IField[] fields = type.getFields();
//build map to filter against
IMethod[] finMeths = resolveFinalMethods(type);
for (int i = 0; i < finMeths.length; i++) {
fFilter.put(createSignatureKey(finMeths[i]), finMeths[i]);
}
IMethod[] filter = type.getMethods();
for (int i = 0; i < filter.length; i++) {
fFilter.put(createSignatureKey(filter[i]), filter[i]);
}
for (int i = 0; i < fields.length; i++) {
IType fieldType = resolveTypeOfField(fields[i]);
if (fieldType == null)
continue;
IMethod[] methods = resolveMethodsHierarchy(fieldType);
List accessMethods = new ArrayList();
//show public methods; hide constructors + final methods
for (int j = 0; j < methods.length; j++) {
boolean publicField = JdtFlags.isPublic(methods[j]);
boolean constructor = methods[j].isConstructor();
boolean finalExist = fFilter.get(createSignatureKey(methods[j])) != null;
if (publicField && !constructor && !finalExist)
accessMethods.add(new Methods2Field(methods[j], fields[i]));
}
Object[] m = accessMethods.toArray();
Methods2Field[] mf = new Methods2Field[m.length];
for (int j = 0; j < m.length; j++) {
mf[j] = (Methods2Field) m[j];
}
fTreeMap.put(fields[i].getElementName(), mf);
fFieldMap.put(fields[i].getElementName(), fields[i]);
}
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IField) {
return (Object[]) fTreeMap.get(((IField) parentElement).getElementName());
}
return null;
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object element) {
return element instanceof IField;
}
public Object[] getElements(Object inputElement) {
if ((inputElement != null) && (inputElement instanceof FieldContentProvider)) {
Object[] o = fTreeMap.keySet().toArray();
Object[] fields = new Object[o.length];
for (int i = 0; i < o.length; i++) {
fields[i] = fFieldMap.get(o[i]);
}
return fields;
}
return null;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
/**to map from dialog results to corresponding fields*/
private static class Methods2Field {
public Methods2Field(IMethod method, IField field) {
fMethod = method;
fField = field;
}
/**method to wrap*/
IMethod fMethod = null;
/**field where method is declared*/
IField fField = null;
}
/**just to wrap JavaElementLabelProvider using my Methods2Field*/
private static class Methods2FieldLabelProvider implements ILabelProvider {
/**Delegate to forward calls*/
JavaElementLabelProvider fMethodLabel = null;
public Methods2FieldLabelProvider() {
fMethodLabel = new JavaElementLabelProvider();
fMethodLabel.turnOn(JavaElementLabelProvider.SHOW_TYPE);
}
public Image getImage(Object element) {
if (element instanceof Methods2Field) {
Methods2Field wrapper = (Methods2Field) element;
return fMethodLabel.getImage(wrapper.fMethod);
} else if (element instanceof IJavaElement) {
return fMethodLabel.getImage(element);
}
return null;
}
public String getText(Object element) {
if (element instanceof Methods2Field) {
Methods2Field wrapper = (Methods2Field) element;
return fMethodLabel.getText(wrapper.fMethod);
} else if (element instanceof IJavaElement) {
return fMethodLabel.getText(element);
}
return null;
}
public void addListener(ILabelProviderListener listener) {
fMethodLabel.addListener(listener);
}
public void dispose() {
fMethodLabel.dispose();
}
public boolean isLabelProperty(Object element, String property) {
return fMethodLabel.isLabelProperty(element, property);
}
public void removeListener(ILabelProviderListener listener) {
fMethodLabel.removeListener(listener);
}
}
/** and a delegate for the sorter*/
private static class Methods2FieldSorter extends ViewerSorter {
JavaElementSorter fSorter = new JavaElementSorter();
public int category(Object element) {
if (element instanceof Methods2Field)
element = ((Methods2Field) element).fMethod;
return fSorter.category(element);
}
public int compare(Viewer viewer, Object e1, Object e2) {
if (e1 instanceof Methods2Field)
e1 = ((Methods2Field) e1).fMethod;
if (e2 instanceof Methods2Field)
e2 = ((Methods2Field) e2).fMethod;
return fSorter.compare(viewer, e1, e2);
}
public Collator getCollator() {
return fSorter.getCollator();
}
}
/**return all methods of all super types, minus dups*/
private static IMethod[] resolveMethodsHierarchy(IType type) throws JavaModelException {
Map map = new HashMap();
IType[] superTypes = JavaModelUtil.getAllSuperTypes(type, new NullProgressMonitor());
addMethodsToMapping(map, type);
for (int i = 0; i < superTypes.length; i++) {
addMethodsToMapping(map, superTypes[i]);
}
return (IMethod[]) map.values().toArray(new IMethod[map.values().size()]);
}
private static void addMethodsToMapping(Map map, IType type) throws JavaModelException {
IMethod[] methods = type.getMethods();
for (int i = 0; i < methods.length; i++) {
map.put(createSignatureKey(methods[i]), methods[i]);
}
}
/**returns a non null array of final methods of the type*/
private static IMethod[] resolveFinalMethods(IType type) throws JavaModelException {
//Interfaces are java.lang.Objects
if (type.isInterface()) {
type = getJavaLangObject(type.getJavaProject());//$NON-NLS-1$
}
IMethod[] methods = resolveMethodsHierarchy(type);
List list = new ArrayList(methods.length);
for (int i = 0; i < methods.length; i++) {
boolean isFinal = Flags.isFinal(methods[i].getFlags());
if (isFinal)
list.add(methods[i]);
}
return (IMethod[]) list.toArray(new IMethod[list.size()]);
}
/**creates a key used for hashmaps for a method signature (name+arguments(fqn))*/
private static String createSignatureKey(IMethod method) throws JavaModelException {
StringBuffer buffer = new StringBuffer();
buffer.append(method.getElementName());
String[] args = method.getParameterTypes();
for (int i = 0; i < args.length; i++) {
String signature;
if (isUnresolved(args[i])) {
int acount = Signature.getArrayCount(args[i]);
if (acount > 0) {
String arg = args[i];
int index = arg.lastIndexOf(Signature.C_ARRAY);
arg = arg.substring(index + 1);
signature = Signature.toString(arg);
} else {
signature = Signature.toString(args[i]);
}
String[][] fqn = method.getDeclaringType().resolveType(signature);
if (fqn != null) {
buffer.append(fqn[0][0]).append('.').append(fqn[0][1]);
//TODO check for [][]
for (int j = 0; j < acount; j++) {
buffer.append("[]"); //$NON-NLS-1$
}
}
}else{
signature=Signature.toString(args[i]);
buffer.append(signature);
}
}
return buffer.toString();
}
private static boolean isUnresolved(String signature) {
boolean flag = false;
char c=Signature.getElementType(signature).charAt(0);
boolean primitive=(c!= Signature.C_RESOLVED && c != Signature.C_UNRESOLVED);
if(primitive)
return flag;
int acount = Signature.getArrayCount(signature);
if (acount > 0) {
int index = signature.lastIndexOf(Signature.C_ARRAY);
c = signature.charAt(index + 1);
} else {
c = signature.charAt(0);
}
switch (c) {
case Signature.C_RESOLVED :
flag=false;
break;
case Signature.C_UNRESOLVED :
flag=true;
break;
default :
throw new IllegalArgumentException();
}
return flag;
}
private static boolean hasPrimitiveType(IField field) throws JavaModelException {
String signature = field.getTypeSignature();
char first = Signature.getElementType(signature).charAt(0);
return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED);
}
/**
* returns Type of field.
*
* if field is primitve null is returned.
* if field is array java.lang.Object is returned.
**/
private static IType resolveTypeOfField(IField field) throws JavaModelException {
boolean isPrimitive = hasPrimitiveType(field);
boolean isArray = isArray(field);
if (!isPrimitive && !isArray) {
String typeName = JavaModelUtil.getResolvedTypeName(field.getTypeSignature(), field.getDeclaringType());
//if the cu has errors its possible no type name is resolved
return typeName != null ? field.getJavaProject().findType(typeName) : null;
} else if (isArray) {
return getJavaLangObject(field.getJavaProject());
}
return null;
}
private static IType getJavaLangObject(IJavaProject project) throws JavaModelException {
return JavaModelUtil.findType(project, "java.lang.Object");//$NON-NLS-1$
}
private static boolean isArray(IField field) throws JavaModelException {
return Signature.getArrayCount(field.getTypeSignature()) > 0;
}
}
|
33,040 |
Bug 33040 No single Undo for generate delegate methods
|
RC 1 - JUnit setup - open TestCase - select fName - generate delegate methods for all String methods - press Ctrl+Z Observe: only one method is removed.
|
resolved fixed
|
e41dc64
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T22:55:44Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddGetterSetterAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.graphics.Image;
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.resource.ImageDescriptor;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Creates getter and setter methods for a type's fields. Opens a dialog
* with a list of fields for which a setter or getter can be generated.
* User is able to check or uncheck items before setters or getters
* are generated.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IField</code> or <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddGetterSetterAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private static final String dialogTitle= ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
/**
* Creates a new <code>AddGetterSetterAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public AddGetterSetterAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddGetterSetterAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddGetterSetterAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddGetterSetterAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddGetterSetterAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
try {
IField[] selectedFields= getSelectedFields(selection);
if (canEnableOn(selectedFields)){
run(selectedFields[0].getDeclaringType(), selectedFields, false);
return;
}
Object firstElement= selection.getFirstElement();
if (firstElement instanceof IType)
run((IType)firstElement, new IField[0], false);
else if (firstElement instanceof ICompilationUnit)
run(((ICompilationUnit) firstElement).findPrimaryType(), new IField[0], false);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException{
if (canEnableOn(getSelectedFields(selection)))
return true;
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType))
return canEnableOn((IType)selection.getFirstElement());
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return canEnableOn(((ICompilationUnit)selection.getFirstElement()).findPrimaryType());
return false;
}
private static boolean canEnableOn(IType type) throws JavaModelException {
if (type == null)
return false;
if (type.getFields().length == 0)
return false;
if (type.getCompilationUnit() == null)
return false;
return true;
}
private static boolean canEnableOn(IField[] fields) throws JavaModelException {
return fields != null && fields.length > 0;
}
private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
if (!ElementValidator.check(type, getShell(), dialogTitle, editor))
return;
if (!ActionUtil.isProcessable(getShell(), type))
return;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ILabelProvider lp= new AddGetterSetterLabelProvider();
Map entries= createGetterSetterMapping(type, settings);
if (entries.isEmpty()){
MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGettSetterAction.typeContainsNoFields.message")); //$NON-NLS-1$
return;
}
ITreeContentProvider cp= new AddGetterSetterContentProvider(entries);
CheckedTreeSelectionDialog dialog= new CheckedTreeSelectionDialog(getShell(), lp, cp);
dialog.setSorter(new JavaElementSorter());
dialog.setTitle(dialogTitle);
String message= ActionMessages.getString("AddGetterSetterAction.dialog.title");//$NON-NLS-1$
dialog.setMessage(message);
dialog.setValidator(createValidator());
dialog.setContainerMode(true);
dialog.setSize(60, 18);
dialog.setInput(type);
dialog.setExpandedElements(type.getFields());
dialog.setInitialSelections(preselected);
dialog.open();
Object[] result= dialog.getResult();
if (result == null)
return;
IField[] getterFields= getGetterFields(result);
IField[] setterFields= getSetterFields(result);
generate(getterFields, setterFields);
}
private static ISelectionStatusValidator createValidator() {
return new ISelectionStatusValidator(){
public IStatus validate(Object[] selection) {
int count= countSelectedMethods(selection);
if (count == 0)
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
if (count == 1)
return new StatusInfo(IStatus.INFO, ActionMessages.getString("AddGetterSetterAction.one_selected")); //$NON-NLS-1$
String message= ActionMessages.getFormattedString("AddGetterSetterAction.methods_selected", String.valueOf(count));//$NON-NLS-1$
return new StatusInfo(IStatus.INFO, message);
}
private int countSelectedMethods(Object[] selection){
int count= 0;
for (int i = 0; i < selection.length; i++) {
if (selection[i] instanceof GetterSetterEntry)
count++;
}
return count;
}
};
}
private static IField[] getGetterFields(Object[] result){
Collection list= new ArrayList(0);
for (int i = 0; i < result.length; i++) {
Object each= result[i];
if ((each instanceof GetterSetterEntry)){
GetterSetterEntry entry= (GetterSetterEntry)each;
if (entry.isGetterEntry)
list.add(entry.field);
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
private static IField[] getSetterFields(Object[] result){
Collection list= new ArrayList(0);
for (int i = 0; i < result.length; i++) {
Object each= result[i];
if ((each instanceof GetterSetterEntry)){
GetterSetterEntry entry= (GetterSetterEntry)each;
if (! entry.isGetterEntry)
list.add(entry.field);
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
private void generate(IField[] getterFields, IField[] setterFields) throws CoreException{
if (getterFields.length == 0 && setterFields.length == 0)
return;
ICompilationUnit cu= null;
if (getterFields.length != 0)
cu= getterFields[0].getCompilationUnit();
else
cu= setterFields[0].getCompilationUnit();
//open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
IField[] workingCopyGetterFields= getWorkingCopyFields(getterFields);
IField[] workingCopySetterFields= getWorkingCopyFields(setterFields);
if (workingCopyGetterFields != null && workingCopySetterFields != null)
run(workingCopyGetterFields, workingCopySetterFields, editor);
}
private IField[] getWorkingCopyFields(IField[] fields) throws CoreException{
if (fields.length == 0)
return new IField[0];
ICompilationUnit cu= fields[0].getCompilationUnit();
ICompilationUnit workingCopyCU;
IField[] workingCopyFields;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyFields= fields;
} else {
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
return null;
}
workingCopyFields= new IField[fields.length];
for (int i= 0; i < fields.length; i++) {
IField field= fields[i];
IField workingCopyField= (IField) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, field);
if (workingCopyField == null) {
showError(ActionMessages.getFormattedString("AddGetterSetterAction.error.fieldNotExisting", field.getElementName())); //$NON-NLS-1$
return null;
}
workingCopyFields[i]= workingCopyField;
}
}
return workingCopyFields;
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
try {
IJavaElement input= SelectionConverter.getInput(fEditor);
if (!ActionUtil.isProcessable(getShell(), input))
return;
IJavaElement[] elements= SelectionConverter.codeResolve(fEditor);
if (elements.length == 1 && (elements[0] instanceof IField)) {
IField field= (IField)elements[0];
run(field.getDeclaringType(), new IField[] {field}, true);
return;
}
IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
if (element != null){
IType type= (IType)element.getAncestor(IJavaElement.TYPE);
if (type != null){
if (type.getFields().length > 0){
run(type, new IField[0], true);
return;
}
}
}
MessageDialog.openInformation(getShell(), dialogTitle,
ActionMessages.getString("AddGetterSetterAction.not_applicable")); //$NON-NLS-1$
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
//---- Helpers -------------------------------------------------------------------
private void run(IField[] getterFields, IField[] setterFields, IEditorPart editor) {
try{
AddGetterSetterOperation op= createAddGetterSetterOperation(getterFields, setterFields);
new ProgressMonitorDialog(getShell()).run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] createdMethods= op.getCreatedAccessors();
if (createdMethods.length > 0) {
EditorUtility.revealInEditor(editor, createdMethods[0]);
}
} catch (InvocationTargetException e) {
String message= ActionMessages.getString("AddGetterSetterAction.error.actionfailed"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), dialogTitle, message);
} catch (InterruptedException e) {
// operation cancelled
}
}
private AddGetterSetterOperation createAddGetterSetterOperation(IField[] getterFields, IField[] setterFields) {
IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
IRequestQuery skipReplaceQuery= skipReplaceQuery();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
return new AddGetterSetterOperation(getterFields, setterFields, settings, skipSetterForFinalQuery, skipReplaceQuery);
}
private IRequestQuery skipSetterForFinalQuery() {
return new IRequestQuery() {
public int doQuery(IMember field) {
// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19367
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.YES_ALL, IRequestQuery.NO, IRequestQuery.CANCEL};
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL};
String fieldName= JavaElementLabels.getElementLabel(field, 0);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipSetterForFinalDialog.message", fieldName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private IRequestQuery skipReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String skipLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skip.label"); //$NON-NLS-1$
String replaceLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.replace.label"); //$NON-NLS-1$
String skipAllLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skipAll.label"); //$NON-NLS-1$
String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) {
final Shell shell= getShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
return IRequestQuery.CANCEL;
}
final int[] result= { MessageDialog.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= ActionMessages.getString("AddGetterSetterAction.QueryDialog.title"); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
private void showError(String message) {
MessageDialog.openError(getShell(), dialogTitle, message);
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements= selection.toList();
int nElements= elements.size();
if (nElements > 0) {
IField[] res= new IField[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IField) {
IField fld= (IField)curr;
if (i == 0) {
// remember the cu of the first element
cu= fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no setters/getters for interfaces
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i]= fld;
} else {
return null;
}
}
return res;
}
return null;
}
private static class GetterSetterEntry {
public final IField field;
public final boolean isGetterEntry;
GetterSetterEntry(IField field, boolean isGetterEntry){
this.field= field;
this.isGetterEntry= isGetterEntry;
}
}
private static class AddGetterSetterLabelProvider extends JavaElementLabelProvider {
AddGetterSetterLabelProvider() {
}
/*
* @see ILabelProvider#getText(Object)
*/
public String getText(Object element) {
if (element instanceof GetterSetterEntry) {
GetterSetterEntry entry= (GetterSetterEntry) element;
try {
if (entry.isGetterEntry) {
return GetterSetterUtil.getGetterName(entry.field, null) + "()"; //$NON-NLS-1$
} else {
return GetterSetterUtil.getSetterName(entry.field, null) + '(' + Signature.getSimpleName(Signature.toString(entry.field.getTypeSignature())) + ')';
}
} catch (JavaModelException e) {
return ""; //$NON-NLS-1$
}
}
return super.getText(element);
}
/*
* @see ILabelProvider#getImage(Object)
*/
public Image getImage(Object element) {
if (element instanceof GetterSetterEntry) {
int flags= 0;
try {
flags= ((GetterSetterEntry) element).field.getFlags();
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
int adornmentFlags= Flags.isStatic(flags) ? JavaElementImageDescriptor.STATIC : 0;
desc= new JavaElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
return JavaPlugin.getImageDescriptorRegistry().get(desc);
}
return super.getImage(element);
}
}
/**
* @return map IField -> GetterSetterEntry[]
*/
private static Map createGetterSetterMapping(IType type, CodeGenerationSettings settings) throws JavaModelException{
IField[] fields= type.getFields();
Map result= new HashMap();
for (int i= 0; i < fields.length; i++) {
List l= new ArrayList(2);
if (GetterSetterUtil.getGetter(fields[i]) == null)
l.add(new GetterSetterEntry(fields[i], true));
if (GetterSetterUtil.getSetter(fields[i]) == null)
l.add(new GetterSetterEntry(fields[i], false));
if (! l.isEmpty())
result.put(fields[i], (GetterSetterEntry[]) l.toArray(new GetterSetterEntry[l.size()]));
}
return result;
}
private static class AddGetterSetterContentProvider implements ITreeContentProvider{
private static final Object[] EMPTY= new Object[0];
private Map fGetterSetterEntries;
public AddGetterSetterContentProvider(Map entries) throws JavaModelException {
fGetterSetterEntries= entries;
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IField)
return (Object[])fGetterSetterEntries.get(parentElement);
return EMPTY;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
if (element instanceof IMember)
return ((IMember)element).getDeclaringType();
if (element instanceof GetterSetterEntry)
return ((GetterSetterEntry)element).field;
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fGetterSetterEntries.keySet().toArray();
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
fGetterSetterEntries.clear();
fGetterSetterEntries= null;
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
}
|
33,040 |
Bug 33040 No single Undo for generate delegate methods
|
RC 1 - JUnit setup - open TestCase - select fName - generate delegate methods for all String methods - press Ctrl+Z Observe: only one method is removed.
|
resolved fixed
|
e41dc64
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T22:55:44Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddUnimplementedConstructorsAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedConstructorsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* Creates unimplemented constructors for a type.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddUnimplementedConstructorsAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
/**
* Creates a new <code>AddUnimplementedConstructorsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public AddUnimplementedConstructorsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddUnimplementedConstructorsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddUnimplementedConstructorsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddUnimplementedConstructorsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddUnimplementedConstructorsAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(checkEnabledEditor());
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
boolean enabled= false;
try {
enabled= getSelectedType(selection) != null;
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
}
setEnabled(enabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
Shell shell= getShell();
try {
IType type= getSelectedType(selection);
if (type == null) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.error.type_removed_in_editor")); //$NON-NLS-1$
return;
}
run(shell, type, editor, false);
} catch (CoreException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
}
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
Shell shell= getShell();
try {
IType type= SelectionConverter.getTypeAtOffset(fEditor);
if (type != null)
run(shell, type, fEditor, true);
else
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.not_applicable")); //$NON-NLS-1$
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
}
}
private boolean checkEnabledEditor() {
return fEditor != null && SelectionConverter.canOperateOn(fEditor);
}
//---- Helpers -------------------------------------------------------------------
private void run(Shell shell, IType type, IEditorPart editor, boolean activatedFromEditor) {
if (!ElementValidator.check(type, getShell(), getDialogTitle(), activatedFromEditor)) {
return;
}
if (!ActionUtil.isProcessable(getShell(), type)) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedConstructorsOperation op= new AddUnimplementedConstructorsOperation(type, settings, false);
try {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(shell);
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.error.nothing_found")); //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
}
private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
Object[] elements= selection.toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("AddUnimplementedConstructorsAction.error.title"); //$NON-NLS-1$
}
}
|
33,040 |
Bug 33040 No single Undo for generate delegate methods
|
RC 1 - JUnit setup - open TestCase - select fName - generate delegate methods for all String methods - press Ctrl+Z Observe: only one method is removed.
|
resolved fixed
|
e41dc64
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T22:55:44Z | 2003-02-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OverrideMethodsAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.OverrideMethodQuery;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* Adds unimplemented methods of a type. Action opens a dialog from
* which the user can chosse the methods to be added.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OverrideMethodsAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
/**
* Creates a new <code>OverrideMethodsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public OverrideMethodsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("OverrideMethodsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("OverrideMethodsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("OverrideMethodsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OverrideMethodsAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(checkEnabledEditor());
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
boolean enabled= false;
try {
enabled= getSelectedType(selection) != null;
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
}
setEnabled(enabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
Shell shell= getShell();
try {
IType type= getSelectedType(selection);
if (type == null || !ElementValidator.check(type, getShell(), getDialogTitle(), false) || !ActionUtil.isProcessable(getShell(), type)) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.error.type_removed_in_editor")); //$NON-NLS-1$
return;
}
run(shell, type, editor);
} catch (CoreException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
}
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
private boolean checkEnabledEditor() {
return fEditor != null && SelectionConverter.canOperateOn(fEditor);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
Shell shell= getShell();
try {
IType type= SelectionConverter.getTypeAtOffset(fEditor);
if (type != null) {
if (!ElementValidator.check(type, shell, getDialogTitle(), false) || !ActionUtil.isProcessable(shell, type)) {
return;
}
run(shell, type, fEditor);
} else {
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.not_applicable")); //$NON-NLS-1$
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
}
}
//---- Helpers -------------------------------------------------------------------
private void run(Shell shell, IType type, IEditorPart editor) {
OverrideMethodQuery selectionQuery= new OverrideMethodQuery(shell, false);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedMethodsOperation op= new AddUnimplementedMethodsOperation(type, settings, selectionQuery, false);
try {
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.error.nothing_found")); //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
}
private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
Object[] elements= selection.toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("OverrideMethodsAction.error.title"); //$NON-NLS-1$
}
}
|
32,585 |
Bug 32585 Organize Import Second Guessing Itself (regression!)
|
file:Outer.java public class Outer{ public static class Inner{ } } ---- file:Client.java import Outer.Inner; public class Client{ { Object innerInstance = new Inner(); } } In build rc1 (I20030221-win32), 'Organize Imports' command flips between adding and removing the statement 'import Outer.Inner;' With the import statement removed, there is no 'Inner' class in scope, and therefore (correctly) causes a compiler error. This has been an issue in the past (I don't recall which version), but was working correctly in the I20030211-win32 build (among others), simply adding the import statement and leaving it be on subsequent organize import invocations. Thanks in advance
|
resolved fixed
|
378dc7f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T23:30:43Z | 2003-02-23T14:20:00Z |
org.eclipse.jdt.ui/core
| |
32,585 |
Bug 32585 Organize Import Second Guessing Itself (regression!)
|
file:Outer.java public class Outer{ public static class Inner{ } } ---- file:Client.java import Outer.Inner; public class Client{ { Object innerInstance = new Inner(); } } In build rc1 (I20030221-win32), 'Organize Imports' command flips between adding and removing the statement 'import Outer.Inner;' With the import statement removed, there is no 'Inner' class in scope, and therefore (correctly) causes a compiler error. This has been an issue in the past (I don't recall which version), but was working correctly in the I20030211-win32 build (among others), simply adding the import statement and leaving it be on subsequent organize import invocations. Thanks in advance
|
resolved fixed
|
378dc7f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-02T23:30:43Z | 2003-02-23T14:20:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
| |
33,266 |
Bug 33266 Internal Error (NPE) during Use Supertype Where Possible
|
Build 2.1 RC 1 1. Select org.eclipse.jface.action.Action 2. Refactor->Use Supertype Where Possible 3. Select IAction 4. Check "Replace the selected supertype..." 5. Press Preview ==> Internal Error. See attached picture and .log
|
resolved fixed
|
0a6bfd6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T11:23:15Z | 2003-02-26T14:33:20Z |
org.eclipse.jdt.ui/core
| |
33,266 |
Bug 33266 Internal Error (NPE) during Use Supertype Where Possible
|
Build 2.1 RC 1 1. Select org.eclipse.jface.action.Action 2. Refactor->Use Supertype Where Possible 3. Select IAction 4. Check "Replace the selected supertype..." 5. Press Preview ==> Internal Error. See attached picture and .log
|
resolved fixed
|
0a6bfd6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T11:23:15Z | 2003-02-26T14:33:20Z |
extension/org/eclipse/jdt/internal/corext/dom/Binding2JavaModel.java
| |
32,932 |
Bug 32932 Restore from local history with UTF16 encoding
|
Build RC1 - change workbench encoding to UTF16 - create a Java class - add a method - delete method in outliner - open "Restore from local History" - select the deleted method - press "Restore" -> garbage in editor
|
resolved fixed
|
5b2fe7d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T12:02:19Z | 2003-02-25T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaCompareUtilities.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.compare;
import java.io.*;
import java.net.*;
import java.util.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.util.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.ui.*;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.ui.text.JavaTextTools;
class JavaCompareUtilities {
static int getTabSize() {
String string= (String) JavaCore.getOptions().get(JavaCore.FORMATTER_TAB_SIZE);
try {
int i= Integer.parseInt(string);
if (i >= 0) {
return i;
}
} catch (NumberFormatException e) {
}
return 4;
}
static String getString(ResourceBundle bundle, String key, String dfltValue) {
if (bundle != null) {
try {
return bundle.getString(key);
} catch (MissingResourceException x) {
}
}
return dfltValue;
}
static String getString(ResourceBundle bundle, String key) {
return getString(bundle, key, key);
}
static int getInteger(ResourceBundle bundle, String key, int dfltValue) {
if (bundle != null) {
try {
String s= bundle.getString(key);
if (s != null)
return Integer.parseInt(s);
} catch (NumberFormatException x) {
} catch (MissingResourceException x) {
}
}
return dfltValue;
}
static ImageDescriptor getImageDescriptor(int type) {
switch (type) {
case IMember.INITIALIZER:
case IMember.METHOD:
return getImageDescriptor("obj16/compare_method.gif"); //$NON-NLS-1$
case IMember.FIELD:
return getImageDescriptor("obj16/compare_field.gif"); //$NON-NLS-1$
case IMember.PACKAGE_DECLARATION:
return JavaPluginImages.DESC_OBJS_PACKDECL;
case IMember.IMPORT_DECLARATION:
return JavaPluginImages.DESC_OBJS_IMPDECL;
case IMember.IMPORT_CONTAINER:
return JavaPluginImages.DESC_OBJS_IMPCONT;
case IMember.COMPILATION_UNIT:
return JavaPluginImages.DESC_OBJS_CUNIT;
}
return ImageDescriptor.getMissingImageDescriptor();
}
static ImageDescriptor getTypeImageDescriptor(boolean isClass) {
if (isClass)
return JavaPluginImages.DESC_OBJS_CLASS;
return JavaPluginImages.DESC_OBJS_INTERFACE;
}
static ImageDescriptor getImageDescriptor(IMember element) {
int t= element.getElementType();
if (t == IMember.TYPE) {
IType type= (IType) element;
try {
return getTypeImageDescriptor(type.isClass());
} catch (CoreException e) {
JavaPlugin.log(e);
return JavaPluginImages.DESC_OBJS_GHOST;
}
}
return getImageDescriptor(t);
}
/**
* Returns a name for the given Java element that uses the same conventions
* as the JavaNode name of a corresponding element.
*/
static String getJavaElementID(IJavaElement je) {
if (je instanceof IMember && ((IMember)je).isBinary())
return null;
StringBuffer sb= new StringBuffer();
switch (je.getElementType()) {
case JavaElement.COMPILATION_UNIT:
sb.append(JavaElement.JEM_COMPILATIONUNIT);
break;
case JavaElement.TYPE:
sb.append(JavaElement.JEM_TYPE);
sb.append(je.getElementName());
break;
case JavaElement.FIELD:
sb.append(JavaElement.JEM_FIELD);
sb.append(je.getElementName());
break;
case JavaElement.METHOD:
sb.append(JavaElement.JEM_METHOD);
sb.append(JavaElementLabels.getElementLabel(je, JavaElementLabels.M_PARAMETER_TYPES));
break;
case JavaElement.INITIALIZER:
String id= je.getHandleIdentifier();
int pos= id.lastIndexOf(JavaElement.JEM_INITIALIZER);
if (pos >= 0)
sb.append(id.substring(pos));
break;
case JavaElement.PACKAGE_DECLARATION:
sb.append(JavaElement.JEM_PACKAGEDECLARATION);
break;
case JavaElement.IMPORT_CONTAINER:
sb.append('<');
break;
case JavaElement.IMPORT_DECLARATION:
sb.append(JavaElement.JEM_IMPORTDECLARATION);
sb.append(je.getElementName());
break;
default:
return null;
}
return sb.toString();
}
/**
* Returns a name which identifies the given typed name.
* The type is encoded as a single character at the beginning of the string.
*/
static String buildID(int type, String name) {
StringBuffer sb= new StringBuffer();
switch (type) {
case JavaNode.CU:
sb.append(JavaElement.JEM_COMPILATIONUNIT);
break;
case JavaNode.CLASS:
case JavaNode.INTERFACE:
sb.append(JavaElement.JEM_TYPE);
sb.append(name);
break;
case JavaNode.FIELD:
sb.append(JavaElement.JEM_FIELD);
sb.append(name);
break;
case JavaNode.CONSTRUCTOR:
case JavaNode.METHOD:
sb.append(JavaElement.JEM_METHOD);
sb.append(name);
break;
case JavaNode.INIT:
sb.append(JavaElement.JEM_INITIALIZER);
sb.append(name);
break;
case JavaNode.PACKAGE:
sb.append(JavaElement.JEM_PACKAGEDECLARATION);
break;
case JavaNode.IMPORT:
sb.append(JavaElement.JEM_IMPORTDECLARATION);
sb.append(name);
break;
case JavaNode.IMPORT_CONTAINER:
sb.append('<');
break;
default:
Assert.isTrue(false);
break;
}
return sb.toString();
}
static ImageDescriptor getImageDescriptor(String relativePath) {
JavaPlugin plugin= JavaPlugin.getDefault();
URL installURL= null;
if (plugin != null)
installURL= plugin.getDescriptor().getInstallURL();
if (installURL != null) {
try {
URL url= new URL(installURL, "icons/full/" + relativePath); //$NON-NLS-1$
return ImageDescriptor.createFromURL(url);
} catch (MalformedURLException e) {
Assert.isTrue(false);
}
}
return null;
}
static Image getImage(IMember member) {
ImageDescriptor id= getImageDescriptor(member);
return id.createImage();
}
static JavaTextTools getJavaTextTools() {
JavaPlugin plugin= JavaPlugin.getDefault();
if (plugin != null)
return plugin.getJavaTextTools();
return null;
}
static IDocumentPartitioner createJavaPartitioner() {
JavaTextTools tools= getJavaTextTools();
if (tools != null)
return tools.createDocumentPartitioner();
return null;
}
/**
* Returns null if an error occurred.
*/
static String readString(InputStream is) {
if (is == null)
return null;
BufferedReader reader= null;
try {
StringBuffer buffer= new StringBuffer();
char[] part= new char[2048];
int read= 0;
reader= new BufferedReader(new InputStreamReader(is, ResourcesPlugin.getEncoding()));
while ((read= reader.read(part)) != -1)
buffer.append(part, 0, read);
return buffer.toString();
} catch (IOException ex) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
JavaPlugin.log(ex);
}
}
}
return null;
}
static byte[] getBytes(String s) {
try {
return s.getBytes(ResourcesPlugin.getEncoding());
} catch (UnsupportedEncodingException e) {
return s.getBytes();
}
}
/**
* Breaks the given string into lines.
*/
static String[] readLines(InputStream is) {
try {
StringBuffer sb= new StringBuffer();
List list= new ArrayList();
while (true) {
int c= is.read();
if (c == -1)
break;
sb.append((char)c);
if (c == '\r') { // single CR or a CR followed by LF
c= is.read();
if (c == -1)
break;
sb.append((char)c);
if (c == '\n') {
list.add(sb.toString());
sb= new StringBuffer();
}
} else if (c == '\n') { // a single LF
list.add(sb.toString());
sb= new StringBuffer();
}
}
if (sb.length() > 0)
list.add(sb.toString());
return (String[]) list.toArray(new String[list.size()]);
} catch (IOException ex) {
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}
}
}
|
31,645 |
Bug 31645 Checking off a method/field in the refactoring wizard navigates list to top
|
See pictures I'll attach afterwards. 1. I navigated to the bottom of the list 2. Checked "measureBlackLevel()" 3. The list navigated to top I expected "3.jpg" instead of "2.jpg". yvind
|
resolved fixed
|
983acd9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T13:45:44Z | 2003-02-12T11:40:00Z |
org.eclipse.jdt.ui/ui
| |
31,645 |
Bug 31645 Checking off a method/field in the refactoring wizard navigates list to top
|
See pictures I'll attach afterwards. 1. I navigated to the bottom of the list 2. Checked "measureBlackLevel()" 3. The list navigated to top I expected "3.jpg" instead of "2.jpg". yvind
|
resolved fixed
|
983acd9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T13:45:44Z | 2003-02-12T11:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/PullPushCheckboxTableViewer.java
| |
16,879 |
Bug 16879 Double click after { does not always select the right block of code.
|
Past the following code in a java text editor public void foo() { String aString = "AAAAAAAAAAAAAAAAA"; String s1[] = new String[]{aString}; String s2[] = new String[]{"aaaa"}; Object o1[] = new Object[][]{{aString},{aString}}; } 1) Doubleclick after { in the line "String s1[]". It will select the code between { and }. Good. 2) Now doubleclick after the first { in the line "String s2[]". It will select aaaa without including the ". It should select everything between { and }. 3) Now doubleclick after the first { in the line "Object o1[]". It will select the contents of the second { instead of the first one.
|
resolved wontfix
|
87cbbdf
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T14:52:10Z | 2002-05-22T15:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaPairMatcher.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.text;
import java.io.IOException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.source.ICharacterPairMatcher;
/**
* JavaPairMatcher.java
*/
/**
* Helper class for match pairs of characters.
*/
public class JavaPairMatcher implements ICharacterPairMatcher {
protected char[] fPairs;
protected IDocument fDocument;
protected int fOffset;
protected int fStartPos;
protected int fEndPos;
protected int fAnchor;
protected JavaCodeReader fReader= new JavaCodeReader();
public JavaPairMatcher(char[] pairs) {
fPairs= pairs;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#match(org.eclipse.jface.text.IDocument, int)
*/
public IRegion match(IDocument document, int offset) {
fOffset= offset;
if (fOffset < 0)
return null;
fDocument= document;
if (fDocument != null && matchPairsAt() && fStartPos != fEndPos)
return new Region(fStartPos, fEndPos - fStartPos + 1);
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#getAnchor()
*/
public int getAnchor() {
return fAnchor;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#dispose()
*/
public void dispose() {
clear();
fDocument= null;
fReader= null;
}
/*
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#clear()
*/
public void clear() {
if (fReader != null) {
try {
fReader.close();
} catch (IOException x) {
// ignore
}
}
}
protected boolean matchPairsAt() {
int i;
int pairIndex1= fPairs.length;
int pairIndex2= fPairs.length;
fStartPos= -1;
fEndPos= -1;
// get the chars preceding and following the start position
try {
char prevChar= fDocument.getChar(Math.max(fOffset - 1, 0));
char nextChar= fDocument.getChar(fOffset);
// search for opening peer character next to the activation point
for (i= 0; i < fPairs.length; i= i + 2) {
if (nextChar == fPairs[i]) {
fStartPos= fOffset;
pairIndex1= i;
} else if (prevChar == fPairs[i]) {
fStartPos= fOffset - 1;
pairIndex1= i;
}
}
// search for closing peer character next to the activation point
for (i= 1; i < fPairs.length; i= i + 2) {
if (prevChar == fPairs[i]) {
fEndPos= fOffset - 1;
pairIndex2= i;
} else if (nextChar == fPairs[i]) {
fEndPos= fOffset;
pairIndex2= i;
}
}
if (fEndPos > -1) {
fAnchor= RIGHT;
fStartPos= searchForOpeningPeer(fEndPos, fPairs[pairIndex2 - 1], fPairs[pairIndex2], fDocument);
if (fStartPos > -1)
return true;
else
fEndPos= -1;
} else if (fStartPos > -1) {
fAnchor= LEFT;
fEndPos= searchForClosingPeer(fStartPos, fPairs[pairIndex1], fPairs[pairIndex1 + 1], fDocument);
if (fEndPos > -1)
return true;
else
fStartPos= -1;
}
} catch (BadLocationException x) {
} catch (IOException x) {
}
return false;
}
protected int searchForClosingPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
fReader.configureForwardReader(document, offset + 1, document.getLength(), true, true);
int stack= 1;
int c= fReader.read();
while (c != JavaCodeReader.EOF) {
if (c == openingPeer && c != closingPeer)
stack++;
else if (c == closingPeer)
stack--;
if (stack == 0)
return fReader.getOffset();
c= fReader.read();
}
return -1;
}
protected int searchForOpeningPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
fReader.configureBackwardReader(document, offset, true, true);
int stack= 1;
int c= fReader.read();
while (c != JavaCodeReader.EOF) {
if (c == closingPeer && c != openingPeer)
stack++;
else if (c == openingPeer)
stack--;
if (stack == 0)
return fReader.getOffset();
c= fReader.read();
}
return -1;
}
}
|
32,082 |
Bug 32082 Creation of { } block captures first line
|
When creating an 'if' or 'for' block, the first line is always captured in the block. I believe this to be a fairly major bug, since it is very possible that when you are writing code you want to insert an if/for/while test into existing code, and definately /not/ end up accidentally capturing a statement. It may have been added in as an idea of productivity recently (don't recall seeing this in 2.1M3 or 4) but it really does not work. 2.1M5 Mac OS X 10.2.4 System.out.println("Before if"); System.out.println("After if"); -> System.out.println("Before if"); if (test) System.out.println("After if"); -> System.out.println("Before if"); if (test) { System.out.println("After if"); } I am reporting this as a major bug; I can't quite feel that it should be a critical bug. However, I do think it should be fixed in 2.1 rather than leaving it, because otherwise people are going to introduce a /lot/ of unneccessary coding errors without realising what is going on.
|
verified fixed
|
37e9f95
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T15:47:58Z | 2003-02-18T01:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/SmartBracesAutoEditStrategy.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.JavaCodeReader;
/**
* An auto edit strategy which inserts the closing brace automatically if possible.
*/
public final class SmartBracesAutoEditStrategy implements IAutoEditStrategy {
/** The text viewer. */
private final ITextViewer fTextViewer;
/** The text input listener. */
private ITextInputListener fTextInputListener;
/** The document listener. */
private final IDocumentListener fDocumentListener= new IDocumentListener() {
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
fSourceRegion= null;
fUndoEvent= null;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
};
/** The last changed caused by user. */
private IRegion fSourceRegion;
/** The undo command to undo the last change caused by auto edit strategy. */
private DocumentEvent fUndoEvent;
private void install(IRegion userRegion, DocumentEvent undoEvent) {
if (userRegion == null || undoEvent == null)
throw new IllegalArgumentException();
fSourceRegion= userRegion;
fUndoEvent= undoEvent;
if (fTextInputListener != null)
return;
IDocument document= fTextViewer.getDocument();
document.addDocumentListener(fDocumentListener);
fTextInputListener= new ITextInputListener() {
/*
* @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)
oldInput.removeDocumentListener(fDocumentListener);
}
/*
* @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)
newInput.addDocumentListener(fDocumentListener);
}
};
fTextViewer.addTextInputListener(fTextInputListener);
}
/**
* Creates a <code>SmartBracesAutoEditStrategy</code>
*/
public SmartBracesAutoEditStrategy(ITextViewer textViewer) {
if (textViewer == null)
throw new IllegalArgumentException();
fTextViewer= textViewer;
}
private boolean isBackspace(DocumentCommand command) {
return
(command.text == null || command.text.length() == 0) &&
fSourceRegion.getOffset() == command.offset && fSourceRegion.getLength() == command.length;
}
private boolean isDelete(DocumentCommand command) {
return
(command.text == null || command.text.length() == 0) &&
fSourceRegion.getOffset() + fSourceRegion.getLength() == command.offset &&
command.length > 0;
}
private boolean isClosingBracket(DocumentCommand command) {
return
command.offset == fSourceRegion.getOffset() + fSourceRegion.getLength() &&
command.length <= 1 && "}".equals(command.text); //$NON-NLS-1$
}
/*
* @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
try {
if (!command.doit)
return;
if (fSourceRegion != null) {
if (isBackspace(command) || isClosingBracket(command)) {
// restore
command.addCommand(fUndoEvent.getOffset(), fUndoEvent.getLength(), fUndoEvent.getText(), fDocumentListener);
command.owner= fDocumentListener;
command.doit= false;
fSourceRegion= null;
fUndoEvent= null;
} else if (isDelete(command)) {
// delete magically inserted text
command.caretOffset= command.offset;
command.offset= fUndoEvent.getOffset();
command.length= fUndoEvent.getLength();
command.text= fUndoEvent.getText();
command.owner= fDocumentListener;
command.doit= false;
fSourceRegion= null;
fUndoEvent= null;
}
} else if (command.text != null && command.text.equals("{")) //$NON-NLS-1$
smartBraces(document, command);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
private static String getLineIndentation(IDocument document, int line, int maxOffset) throws BadLocationException {
int lineOffset= document.getLineOffset(line);
String string= document.get(lineOffset, maxOffset - lineOffset);
final int length= string.length();
int i= 0;
while (i != length && Character.isWhitespace(string.charAt(i)))
++i;
return string.substring(0, i);
}
private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) throws BadLocationException {
final String source= document.get(scanRegion.getOffset(), scanRegion.getLength());
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
scanner.setSource(source.toCharArray());
try {
int id= scanner.getNextToken();
while (id != ITerminalSymbols.TokenNameEOF && id != tokenId)
id= scanner.getNextToken();
if (id == ITerminalSymbols.TokenNameEOF)
return null;
int tokenOffset= scanner.getCurrentTokenStartPosition();
int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end
return new Region(tokenOffset + scanRegion.getOffset(), tokenLength);
} catch (InvalidInputException e) {
return null;
}
}
private void addReplace(IDocument document, DocumentCommand command, int offset, int length, String text) throws BadLocationException {
command.addCommand(offset, length, text, fDocumentListener); //$NON-NLS-1$
command.owner= fDocumentListener;
command.doit= false;
String oldText= document.get(offset, length);
int delta= offset <= command.offset ? 0 : (command.text == null ? 0 : command.text.length()) - command.length;
IRegion replacedRegion= new Region(command.offset, command.text == null ? 0 : command.text.length());
DocumentEvent undoEvent= new DocumentEvent(document, offset + delta, text == null ? 0 : text.length(), oldText);
install(replacedRegion, undoEvent);
}
/**
* Closes the block immediately on the next line.
*/
private void makeBlock(IDocument document, DocumentCommand command) throws BadLocationException {
int offset= command.offset;
int insertionLine= document.getLineOfOffset(offset);
final String lineDelimiter= getLineDelimiter(document);
final String lineIndentation= getLineIndentation(document, insertionLine, offset);
final StringBuffer buffer= new StringBuffer();
buffer.append(lineIndentation);
buffer.append("}"); //$NON-NLS-1$
buffer.append(lineDelimiter);
// skip line delimiter, otherwise it may clash with the insertion of '{'
int replaceOffset= document.getLineOffset(insertionLine) + document.getLineLength(insertionLine);
addReplace(document, command, replaceOffset, 0, buffer.toString());
}
/**
* Surrounds a statement with a block.
*/
private void makeBlock(IDocument document, DocumentCommand command, IRegion replace, IRegion statement, IRegion nextStatement, IRegion prevStatement, boolean followingControl) throws BadLocationException {
final int insertionLine= document.getLineOfOffset(replace.getOffset());
final int statementLine= document.getLineOfOffset(statement.getOffset() + statement.getLength());
final int statementLineBegin= document.getLineOfOffset(statement.getOffset());
final String outerSpace= (prevStatement.getOffset() + prevStatement.getLength() == replace.getOffset()) ? "" : " "; //$NON-NLS-1$ //$NON-NLS-2$
final String innerSpace= (replace.getOffset() + replace.getLength() == statement.getOffset()) ? "" : " "; //$NON-NLS-1$ //$NON-NLS-2$
switch (statementLine - insertionLine) {
// statement on same line
case 0:
{
int replaceOffset= statement.getOffset() + statement.getLength();
int replaceLength= document.getChar(replaceOffset) == ' ' ? 1 : 0; // eat existing space
addReplace(document, command, replaceOffset, replaceLength, innerSpace + "}" + outerSpace); //$NON-NLS-1$
}
break;
// more than one line distance between block begin and next statement:
default:
// statement on next line
case 1:
// statement is too far away, assume normal typing; add closing braces before statement
if (statementLineBegin - insertionLine >= 2) {
makeBlock(document, command);
break;
}
final String lineDelimiter= getLineDelimiter(document);
final String lineIndentation= getLineIndentation(document, insertionLine, replace.getOffset());
final StringBuffer buffer= new StringBuffer();
if (nextStatement == null) {
buffer.append(lineDelimiter);
buffer.append(lineIndentation);
buffer.append("}"); //$NON-NLS-1$
// at end of line to skip a possible comment
IRegion region= document.getLineInformation(statementLine);
addReplace(document, command, region.getOffset() + region.getLength(), 0, buffer.toString());
} else {
final int nextStatementLine=document.getLineOfOffset(nextStatement.getOffset());
if (statementLine == nextStatementLine) {
int replaceOffset= statement.getOffset() + statement.getLength();
int replaceLength= document.getChar(replaceOffset) == ' ' ? 1 : 0; // eat existing space
addReplace(document, command, replaceOffset, replaceLength, innerSpace + "}" + outerSpace); //$NON-NLS-1$
} else {
if (followingControl && JavaCore.DO_NOT_INSERT.equals(JavaCore.getOption(JavaCore.FORMATTER_NEWLINE_CONTROL))) {
addReplace(document, command, nextStatement.getOffset(), 0, "}" + outerSpace); //$NON-NLS-1$
} else {
buffer.append(lineDelimiter);
buffer.append(lineIndentation);
buffer.append("}"); //$NON-NLS-1$
// at end of line to skip a possible comment
IRegion region= document.getLineInformation(statementLine);
addReplace(document, command, region.getOffset() + region.getLength(), 0, buffer.toString());
}
}
}
break;
}
}
private static Statement getNextStatement(Statement statement) {
ASTNode node= statement.getParent();
while (node != null && node.getNodeType() != ASTNode.BLOCK)
node= node.getParent();
if (node == null)
return null;
Block block= (Block) node;
List statements= block.statements();
for (final Iterator iterator= statements.iterator(); iterator.hasNext(); ) {
final Statement nextStatement= (Statement) iterator.next();
if (nextStatement.getStartPosition() >= statement.getStartPosition() + statement.getLength())
return nextStatement;
}
return null;
}
private static class CompilationUnitInfo{
public CompilationUnitInfo(char[] buffer, int delta) {
this.buffer= buffer;
this.delta= delta;
}
public char[] buffer;
public int delta;
}
private static boolean areBlocksConsistent(IDocument document, int offset) {
JavaCodeReader reader= new JavaCodeReader();
try {
int begin= offset;
int end= offset;
while (true) {
begin= searchForOpeningPeer(reader, begin, '{', '}', document);
end= searchForClosingPeer(reader, end, '{', '}', document);
if (begin == -1 && end == -1)
return true;
if (begin == -1 || end == -1)
return false;
}
} catch (IOException e) {
return false;
}
}
private static IRegion getSurroundingBlock(IDocument document, int offset) {
JavaCodeReader reader= new JavaCodeReader();
try {
int begin= searchForOpeningPeer(reader, offset, '{', '}', document);
int end= searchForClosingPeer(reader, offset, '{', '}', document);
if (begin == -1 || end == -1)
return null;
return new Region(begin, end + 1 - begin);
} catch (IOException e) {
return null;
}
}
private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset) {
try {
IRegion sourceRange= getSurroundingBlock(document, offset);
if (sourceRange == null)
return null;
String source= document.get(sourceRange.getOffset(), sourceRange.getLength());
StringBuffer contents= new StringBuffer();
contents.append("class C{void m()"); //$NON-NLS-1$
final int methodOffset= contents.length();
contents.append(source);
contents.append('}');
char[] buffer= contents.toString().toCharArray();
return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private static IRegion createRegion(ASTNode node, int delta) {
if (node == null)
return null;
return new Region(node.getStartPosition() + delta, node.getLength());
}
private void smartBraces(IDocument document, DocumentCommand command) throws BadLocationException {
if (! JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES))
return;
final int offset= command.offset;
final int length= command.length;
final IRegion replace= new Region(offset, length);
CompilationUnitInfo info= getCompilationUnitForMethod(document, offset);
if (info == null)
return;
char[] buffer= info.buffer;
int delta= info.delta; // offset of buffer inside document
final CompilationUnit compilationUnit= AST.parseCompilationUnit(buffer);
// continue only if no problems exist in this method
IProblem[] problems= compilationUnit.getProblems();
for (int i= 0; i != problems.length; ++i)
if (problems[i].getID() == IProblem.UnmatchedBracket)
return;
ASTNode node= NodeFinder.perform(compilationUnit, offset - delta, length);
if (node == null)
return;
// get truly enclosing node
while (node != null && length == 0 && (offset - delta == node.getStartPosition() || offset - delta == node.getStartPosition() + node.getLength()))
node= node.getParent();
switch (node.getNodeType()) {
case ASTNode.BLOCK:
// normal typing: no useful AST node available
if (areBlocksConsistent(document, offset))
makeBlock(document, command);
break;
case ASTNode.IF_STATEMENT:
{
IfStatement ifStatement= (IfStatement) node;
Expression expression= ifStatement.getExpression();
Statement thenStatement= ifStatement.getThenStatement();
Statement elseStatement= ifStatement.getElseStatement();
Statement nextStatement= getNextStatement(ifStatement);
IRegion expressionRegion= createRegion(expression, delta);
IRegion thenRegion= createRegion(thenStatement, delta);
IRegion elseRegion= createRegion(elseStatement, delta);
IRegion nextRegion= createRegion(nextStatement, delta);
IRegion elseToken= null;
if (elseStatement != null) {
int sourceOffset= thenRegion.getOffset() + thenRegion.getLength();
int sourceLength= elseRegion.getOffset() - sourceOffset;
elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse);
}
// between expression and then statement
if (offset >= expressionRegion.getOffset() + expressionRegion.getLength() &&
offset + length <= thenRegion.getOffset())
{
if (thenStatement == null || thenStatement.getNodeType() == ASTNode.BLOCK)
return;
if (elseToken != null)
nextRegion= elseToken;
// search for )
int sourceOffset= expressionRegion.getOffset() + expressionRegion.getLength();
int sourceLength= thenRegion.getOffset() - sourceOffset;
IRegion rightParenthesisToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameRPAREN);
makeBlock(document, command, replace, thenRegion, nextRegion, rightParenthesisToken, elseStatement != null);
break;
}
if (elseStatement == null || elseStatement.getNodeType() == ASTNode.BLOCK)
return;
// between then and else and
if (offset >= elseToken.getOffset() + elseToken.getLength() && offset + length <= elseRegion.getOffset())
makeBlock(document, command, replace, createRegion(elseStatement, delta), nextRegion, elseToken, false);
}
break;
case ASTNode.WHILE_STATEMENT:
case ASTNode.FOR_STATEMENT:
{
Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT
? ((WhileStatement) node).getExpression()
: ((ForStatement) node).getExpression();
Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT
? ((WhileStatement) node).getBody()
: ((ForStatement) node).getBody();
Statement nextStatement= getNextStatement((Statement) node);
if (expression == null || body == null || body.getNodeType() == ASTNode.BLOCK)
return;
IRegion expressionRegion= createRegion(expression, delta);
IRegion bodyRegion= createRegion(body, delta);
IRegion nextRegion= createRegion(nextStatement, delta);
// search for )
int sourceOffset= expressionRegion.getOffset() + expressionRegion.getLength();
int sourceLength= bodyRegion.getOffset() - sourceOffset;
IRegion rightParenthesisToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameRPAREN);
if (offset >= expressionRegion.getOffset() + expressionRegion.getLength() && offset + length <= bodyRegion.getOffset())
makeBlock(document, command, replace, bodyRegion, nextRegion, rightParenthesisToken, false);
}
break;
case ASTNode.DO_STATEMENT:
{
DoStatement doStatement= (DoStatement) node;
Statement body= doStatement.getBody();
Expression expression= doStatement.getExpression();
//Statement nextStatement= getNextStatement((Statement) node);
if (expression == null || body == null || body.getNodeType() == ASTNode.BLOCK)
return;
IRegion doRegion= createRegion(doStatement, delta);
IRegion bodyRegion= createRegion(body, delta);
IRegion expressionRegion= createRegion(expression, delta);
//IRegion nextRegion= createRegion(nextStatement, delta);
int sourceOffset= bodyRegion.getOffset() + bodyRegion.getLength();
int sourceLength= expressionRegion.getOffset() - sourceOffset;
IRegion whileToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNamewhile);
IRegion prevRegion= getToken(document, doRegion, ITerminalSymbols.TokenNamedo);
if (offset >= doRegion.getOffset() && offset + length <= bodyRegion.getOffset())
makeBlock(document, command, replace, bodyRegion, whileToken, prevRegion, true);
}
break;
default:
break;
}
}
private static int searchForClosingPeer(JavaCodeReader reader, int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
reader.configureForwardReader(document, offset + 1, document.getLength(), true, true);
int stack= 1;
int c= reader.read();
while (c != JavaCodeReader.EOF) {
if (c == openingPeer && c != closingPeer)
stack++;
else if (c == closingPeer)
stack--;
if (stack == 0)
return reader.getOffset();
c= reader.read();
}
return -1;
}
private static int searchForOpeningPeer(JavaCodeReader reader, int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
reader.configureBackwardReader(document, offset, true, true);
int stack= 1;
int c= reader.read();
while (c != JavaCodeReader.EOF) {
if (c == closingPeer && c != openingPeer)
stack++;
else if (c == openingPeer)
stack--;
if (stack == 0)
return reader.getOffset();
c= reader.read();
}
return -1;
}
}
|
33,405 |
Bug 33405 Refactoring extract local variable fails in nested if statements
|
If a local variable is extracted from a nested if statement, and it only exists in the second case onwards, then the variable is positioned incorrectly between the if cases. String x; boolean test,test2,test3; if (test) { } else if (test2) { x = "ExtractMe"; } else if (test3) { x = "ExtractMe"; } -> highlight "ExtractMe" and extract to local variable 'defect' if (test) { } else final String defect = "ExtractMe"; if (test2) { x = defect; } else if (test3) { x = defect; } Of course, if the first test block also refers to "ExtractMe" then it will work properly and put the final variable declaration above the whole nested if loop. Eclipse 2.1RC1 Windows 2000, Mac OS X.2.4
|
verified fixed
|
8e802bb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T16:53:57Z | 2003-02-27T01:40:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
33,405 |
Bug 33405 Refactoring extract local variable fails in nested if statements
|
If a local variable is extracted from a nested if statement, and it only exists in the second case onwards, then the variable is positioned incorrectly between the if cases. String x; boolean test,test2,test3; if (test) { } else if (test2) { x = "ExtractMe"; } else if (test3) { x = "ExtractMe"; } -> highlight "ExtractMe" and extract to local variable 'defect' if (test) { } else final String defect = "ExtractMe"; if (test2) { x = defect; } else if (test3) { x = defect; } Of course, if the first test block also refers to "ExtractMe" then it will work properly and put the final variable declaration above the whole nested if loop. Eclipse 2.1RC1 Windows 2000, Mac OS X.2.4
|
verified fixed
|
8e802bb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-03-03T16:53:57Z | 2003-02-27T01:40:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.