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
11,828
Bug 11828 Can cause NPE: Open Recent... is active when no perspective is open
1. open 2 java files (A and B) 2. close all perspectives 3. Open Recent... (should be diabled) 4. Open file A 5. Open file B ==> icons appear in the toolbar Click next error ==> NPE Log: Wed Mar 20 14:11:39 GMT+01:00 2002 2 org.eclipse.ui 2 Problems occurred when invoking code from plug-in: org.eclipse.ui. java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider.update(JavaInformationProvider.java:89) at org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider$EditorWatcher.partActivated(JavaInformationProvider.java:54) at org.eclipse.ui.internal.PartListenerList$1.run(PartListenerList.java:37) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:817) at org.eclipse.core.runtime.Platform.run(Platform.java:395) at org.eclipse.ui.internal.PartListenerList.firePartActivated(PartListenerList.java:35) at org.eclipse.ui.internal.WWinPartService.partActivated(WWinPartService.java:102) at org.eclipse.ui.internal.PartListenerList$1.run(PartListenerList.java:37) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:817) at org.eclipse.core.runtime.Platform.run(Platform.java:395) at org.eclipse.ui.internal.PartListenerList.firePartActivated(PartListenerList.java:35) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated(WorkbenchPage.java:696) at org.eclipse.ui.internal.WorkbenchPage.setActivePart(WorkbenchPage.java:1683) at org.eclipse.ui.internal.WorkbenchPage.activate(WorkbenchPage.java:103) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:1277) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:1254) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:1246) at org.eclipse.ui.internal.ReopenEditorMenu.open(ReopenEditorMenu.java:195) at org.eclipse.ui.internal.ReopenEditorMenu$1.widgetSelected(ReopenEditorMenu.java:163) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:698) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52) Log: Wed Mar 20 14:11:40 GMT+01:00 2002 1 org.eclipse.core.resources 4 Unhandled exception caught in event loop. Log: Wed Mar 20 14:11:40 GMT+01:00 2002 4 org.eclipse.ui 0 java.lang.NullPointerException java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.GotoErrorAction.run(GotoErrorAction.java:32) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:698) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
closed fixed
6e927a6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T10:49:08Z
2002-03-20T13:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaInformationProvider.java
package org.eclipse.jdt.internal.ui.text.java.hover; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; import org.eclipse.jdt.ui.*; import org.eclipse.jdt.ui.text.java.hover.*; public class JavaInformationProvider implements IInformationProvider { class EditorWatcher implements IPartListener { /** * @see IPartListener#partOpened(IWorkbenchPart) */ public void partOpened(IWorkbenchPart part) { } /** * @see IPartListener#partDeactivated(IWorkbenchPart) */ public void partDeactivated(IWorkbenchPart part) { } /** * @see IPartListener#partClosed(IWorkbenchPart) */ public void partClosed(IWorkbenchPart part) { if (part == fEditor) { fEditor.getSite().getWorkbenchWindow().getPartService().removePartListener(fPartListener); fPartListener= null; } } /** * @see IPartListener#partActivated(IWorkbenchPart) */ public void partActivated(IWorkbenchPart part) { update(); } public void partBroughtToTop(IWorkbenchPart part) { update(); } }; protected IEditorPart fEditor; protected IPartListener fPartListener; protected String fCurrentPerspective; protected IJavaEditorTextHover fImplementation; public JavaInformationProvider(IEditorPart editor) { fEditor= editor; if (fEditor != null) { fPartListener= new EditorWatcher(); IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow(); window.getPartService().addPartListener(fPartListener); update(); } } protected void update() { IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow(); IWorkbenchPage page= window.getActivePage(); if (page != null) { String newPerspective= page.getPerspective().getId(); if (fCurrentPerspective == null || fCurrentPerspective != newPerspective) { fCurrentPerspective= newPerspective; fImplementation= new JavaTypeHover(); fImplementation.setEditor(fEditor); } } } /* * @see IInformationProvider#getSubject(ITextViewer, int) */ public IRegion getSubject(ITextViewer textViewer, int offset) { if (textViewer != null) return JavaWordFinder.findWord(textViewer.getDocument(), offset); return null; } /* * @see IInformationProvider#getInformation(ITextViewer, IRegion) */ public String getInformation(ITextViewer textViewer, IRegion subject) { if (fImplementation != null) { String s= fImplementation.getHoverInfo(textViewer, subject); if (s != null && s.trim().length() > 0) return s; } return null; } }
11,866
Bug 11866 Wrong labels in Update Test Suite dialog
"Test Classes to be included" is written with TestClasses (missing space) The status line talks about methods being selected instead of types. The action name is written together (TestSuite) instead of Test Suite
resolved fixed
790bdf0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T12:02:02Z
2002-03-20T16:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); updateStatus(findMostSevereStatus()); // put default class to test if (element != null) { IType enclosingType= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { enclosingType= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) enclosingType= JavaModelUtil.findPrimaryType(cu); } if (enclosingType != null) { try { if (!TestSearchEngine.isTestImplementor(enclosingType)) { fDefaultClassToTest= enclosingType.getFullyQualifiedName(); } } catch (JavaModelException e) { e.printStackTrace(); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return NewTestCaseCreationWizardPage.getMostSevere(new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } updateStatus(findMostSevereStatus()); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); setFocus(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { // ??? } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. * @param canBeModified Selects if the super class can be changed by the user */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type) throws JavaModelException { String constr= "public "+getTypeName()+"(String name) {super(name);}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(constr, null, false, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp; IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { setUp="/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown; IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; methodName.append(param.substring( ((param.startsWith( (new Character(Signature.C_UNRESOLVED)).toString() ,start))?start+1:start) , ((param.endsWith( (new Character(Signature.C_NAME_END)).toString() ))?end-1:end)) ); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } if (newMethodsNames.contains(methodName.toString())) methodName.append("1"); //$NON-NLS-1$ newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } protected static GridData gridDataForDefaultForTypeName(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } public static Control createEmptySpace(Composite parent, int span) { Label label= new Label(parent, SWT.LEFT); GridData gd= new GridData(); gd.horizontalAlignment= gd.BEGINNING; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= span; gd.horizontalIndent= 0; gd.widthHint= 0; gd.heightHint= 0; label.setLayoutData(gd); return label; } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists fFirstTime= false; } } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { System.err.println(this.getClass()+": checkSuperClass(): "+e); //$NON-NLS-1$ } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see WizardPage#getNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); if (!val.isOK()) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ return status; } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.interface_not_visible",classToTestName));//$NON-NLS-1$ return status; } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Finds the most severe status from a array of stati. * An error is more severe than a warning, and a warning is more severe * than ok. */ public static IStatus getMostSevere(IStatus[] status) { IStatus max= null; for (int i= 0; i < status.length; i++) { IStatus curr= status[i]; if (curr.matches(IStatus.ERROR)) { return curr; } if (max == null || curr.getSeverity() > max.getSeverity()) { max= curr; } } return max; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); } }
11,866
Bug 11866 Wrong labels in Update Test Suite dialog
"Test Classes to be included" is written with TestClasses (missing space) The status line talks about methods being selected instead of types. The action name is written together (TestSuite) instead of Test Suite
resolved fixed
790bdf0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T12:02:02Z
2002-03-20T16:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage2.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.util.ArrayList; import java.util.Arrays; import java.util.Vector; 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.internal.ui.viewsupport.ContainerCheckedTreeViewer; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; /** * Wizard page to select the methods from a class under test. */ public class NewTestCaseCreationWizardPage2 extends WizardPage { private final static String PAGE_NAME= "NewTestCaseCreationWizardPage2"; //$NON-NLS-1$ public final static String PREFIX= "test"; //$NON-NLS-1$ private NewTestCaseCreationWizardPage fFirstPage; private IType fClassToTest; private Button fCreateTasksButton; private ContainerCheckedTreeViewer fMethodsTree; private Button fSelectAllButton; private Button fDeselectAllButton; private Label fSelectedMethodsLabel; /** * Constructor for NewTestCaseCreationWizardPage2. */ protected NewTestCaseCreationWizardPage2(NewTestCaseCreationWizardPage firstPage) { super(PAGE_NAME); fFirstPage= firstPage; setTitle(Messages.getString("NewTestClassWizPage2.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage2.description")); //$NON-NLS-1$ } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { Composite container= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; container.setLayout(layout); createMethodsTreeControls(container); createSpacer(container); createTasksControls(container); setControl(container); } protected void createTasksControls(Composite container) { GridLayout layout; GridData gd; Composite prefixContainer= new Composite(container, SWT.NONE); gd= new GridData(); gd.horizontalAlignment = GridData.FILL; gd.horizontalSpan = 2; prefixContainer.setLayoutData(gd); layout = new GridLayout(); layout.numColumns = 2; layout.marginWidth = 0; layout.marginHeight = 0; prefixContainer.setLayout(layout); fCreateTasksButton= new Button(prefixContainer, SWT.CHECK | SWT.LEFT); fCreateTasksButton.setText(Messages.getString("NewTestClassWizPage2.create_tasks.text")); //$NON-NLS-1$ fCreateTasksButton.setEnabled(true); fCreateTasksButton.setSelection(true); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.horizontalSpan= 2; fCreateTasksButton.setLayoutData(gd); } protected void createMethodsTreeControls(Composite container) { Label label= new Label(container, SWT.LEFT | SWT.WRAP); label.setFont(container.getFont()); label.setText(Messages.getString("NewTestClassWizPage2.methods_tree.label")); //$NON-NLS-1$ GridData gd = new GridData(); gd.horizontalSpan = 2; label.setLayoutData(gd); fMethodsTree= new ContainerCheckedTreeViewer(container, SWT.BORDER); gd= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL); gd.heightHint= 180; fMethodsTree.getTree().setLayoutData(gd); fMethodsTree.setLabelProvider(new JavaElementLabelProvider()); fMethodsTree.setAutoExpandLevel(2); fMethodsTree.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { updateSelectedMethodsLabel(); } }); Composite buttonContainer= new Composite(container, SWT.NONE); gd= new GridData(GridData.FILL_VERTICAL); buttonContainer.setLayoutData(gd); GridLayout buttonLayout= new GridLayout(); buttonLayout.marginWidth= 0; buttonLayout.marginHeight= 0; buttonContainer.setLayout(buttonLayout); fSelectAllButton= new Button(buttonContainer, SWT.PUSH); fSelectAllButton.setText(Messages.getString("NewTestClassWizPage2.selectAll")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fSelectAllButton.setLayoutData(gd); fSelectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fMethodsTree.setCheckedElements((Object[]) fMethodsTree.getInput()); updateSelectedMethodsLabel(); } }); fDeselectAllButton= new Button(buttonContainer, SWT.PUSH); fDeselectAllButton.setText(Messages.getString("NewTestClassWizPage2.deselectAll")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fDeselectAllButton.setLayoutData(gd); fDeselectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fMethodsTree.setCheckedElements(new Object[0]); updateSelectedMethodsLabel(); } }); /* No of selected methods label */ fSelectedMethodsLabel= new Label(container, SWT.LEFT); fSelectedMethodsLabel.setFont(container.getFont()); updateSelectedMethodsLabel(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan= 1; fSelectedMethodsLabel.setLayoutData(gd); Label emptyLabel= new Label(container, SWT.LEFT); gd= new GridData(); gd.horizontalSpan= 1; emptyLabel.setLayoutData(gd); } protected void createSpacer(Composite container) { Label spacer= new Label(container, SWT.NONE); GridData data= new GridData(); data.horizontalSpan= 2; data.horizontalAlignment= GridData.FILL; data.verticalAlignment= GridData.BEGINNING; data.heightHint= 4; spacer.setLayoutData(data); } public void setVisible(boolean visible) { if (visible) { fClassToTest= fFirstPage.getClassToTest(); IType currType= fClassToTest; ArrayList types= null; try { ITypeHierarchy hierarchy= currType.newSupertypeHierarchy(null); IType[] superTypes= hierarchy.getAllSuperclasses(currType); types= new ArrayList(superTypes.length+1); types.add(currType); types.addAll(Arrays.asList(superTypes)); } catch(JavaModelException e) { } fMethodsTree.setContentProvider(new MethodsTreeContentProvider(types.toArray())); if (types == null) types= new ArrayList(); fMethodsTree.setInput(types.toArray()); fMethodsTree.setSelection(new StructuredSelection(currType), true); } updateSelectedMethodsLabel(); super.setVisible(visible); } public IMethod[] getCheckedMethods() { Object[] checkedObjects= fMethodsTree.getCheckedElements(); int methodCount= 0; for (int i = 0; i < checkedObjects.length; i++) { if (checkedObjects[i] instanceof IMethod) methodCount++; } IMethod[] checkedMethods= new IMethod[methodCount]; int j= 0; for (int i = 0; i < checkedObjects.length; i++) { if (checkedObjects[i] instanceof IMethod) { checkedMethods[j]= (IMethod)checkedObjects[i]; j++; } } return checkedMethods; } private static class MethodsTreeContentProvider implements ITreeContentProvider { private Object[] fTypes; private IMethod[] fMethods; private final Object[] fEmpty= new Object[0]; public MethodsTreeContentProvider(Object[] types) { fTypes= types; Vector methods= new Vector(); for (int i = types.length-1; i > -1; i--) { Object object = types[i]; if (object instanceof IType) { IType type = (IType) object; try { IMethod[] currMethods= type.getMethods(); for_currMethods: for (int j = 0; j < currMethods.length; j++) { IMethod currMethod = currMethods[j]; int flags= currMethod.getFlags(); if (!Flags.isPrivate(flags)) { for (int k = 0; k < methods.size(); k++) { IMethod m= ((IMethod)methods.get(k)); if (m.getElementName().equals(currMethod.getElementName()) && m.getSignature().equals(currMethod.getSignature())) { methods.set(k,currMethod); continue for_currMethods; } } methods.add(currMethod); } } } catch (JavaModelException e) { System.err.println("MethodsTreeContentProvider: "+e); //$NON-NLS-1$ } } } fMethods= new IMethod[methods.size()]; methods.copyInto(fMethods); } /* * @see ITreeContentProvider#getChildren(Object) */ public Object[] getChildren(Object parentElement) { if (parentElement instanceof IType) { IType parentType= (IType)parentElement; ArrayList result= new ArrayList(fMethods.length); for (int i= 0; i < fMethods.length; i++) { if (fMethods[i].getDeclaringType().equals(parentType)) { result.add(fMethods[i]); } } return result.toArray(); } return fEmpty; } /* * @see ITreeContentProvider#getParent(Object) */ public Object getParent(Object element) { if (element instanceof IMethod) return ((IMethod)element).getDeclaringType(); 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 fTypes; } /* * @see IContentProvider#dispose() */ public void dispose() { } /* * @see IContentProvider#inputChanged(Viewer, Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public IMethod[] getAllMethods() { return fMethods; } } public boolean getCreateTasksButtonSelection() { return fCreateTasksButton.getSelection(); } private void updateSelectedMethodsLabel() { Object[] checked= fMethodsTree.getCheckedElements(); int checkedMethodCount= 0; for (int i= 0; i < checked.length; i++) { if (checked[i] instanceof IMethod) checkedMethodCount++; } fSelectedMethodsLabel.setText(Messages.getFormattedString(((checkedMethodCount==1)?"NewTestClassWizPage2.selected_methods.label_one":"NewTestClassWizPage2.selected_methods.label_many"), new Integer(checkedMethodCount))); //$NON-NLS-1$ //$NON-NLS-2$ } public IMethod[] getAllMethods() { return ((MethodsTreeContentProvider)fMethodsTree.getContentProvider()).getAllMethods(); } }
11,866
Bug 11866 Wrong labels in Update Test Suite dialog
"Test Classes to be included" is written with TestClasses (missing space) The status line talks about methods being selected instead of types. The action name is written together (TestSuite) instead of Test Suite
resolved fixed
790bdf0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T12:02:02Z
2002-03-20T16:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestSuiteCreationWizard.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.IEditorPart; /** * A wizard for creating TestSuites. */ public class NewTestSuiteCreationWizard extends JUnitWizard { private NewTestSuiteCreationWizardPage fPage; public NewTestSuiteCreationWizard() { super(); //setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS); //setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); //setWindowTitle(NewWizardMessages.getString("NewClassCreationWizard.title")); //$NON-NLS-1$ } /* * @see Wizard#createPages */ public void addPages() { super.addPages(); //IWorkspace workspace= JavaPlugin.getWorkspace(); IWorkspace workspace= ResourcesPlugin.getWorkspace(); fPage= new NewTestSuiteCreationWizardPage(); addPage(fPage); fPage.init(getSelection()); } /* * @see Wizard#performFinish */ public boolean performFinish() { IPackageFragment pack= fPage.getPackageFragment(); String filename= fPage.getTypeName() + ".java"; //$NON-NLS-1$ ICompilationUnit cu= pack.getCompilationUnit(filename); if (cu.exists()) { IEditorPart cu_ep= EditorUtility.isOpenInEditor(cu); if (cu_ep != null && cu_ep.isDirty()) { boolean saveUnsavedChanges= MessageDialog.openQuestion(fPage.getShell(), Messages.getString("NewTestSuiteWiz.unsavedchangesDialog.title"), Messages.getFormattedString("NewTestSuiteWiz.unsavedchangesDialog.message", filename)); //$NON-NLS-1$ //$NON-NLS-2$ if (saveUnsavedChanges) { ProgressMonitorDialog progressDialog= new ProgressMonitorDialog(fPage.getShell()); try { progressDialog.run(false, false, getRunnableSave(cu_ep)); } catch (Exception e) { e.printStackTrace(); } } } IType suiteType= cu.getType(fPage.getTypeName()); IMethod suiteMethod= suiteType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (suiteMethod.exists()) { try { ISourceRange range= suiteMethod.getSourceRange(); IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); int start= originalContent.indexOf(NewTestSuiteCreationWizardPage.startMarker); if (start > -1) { int end= originalContent.indexOf(NewTestSuiteCreationWizardPage.endMarker, start); if (end < 0) { fPage.cannotUpdateSuiteError(); return false; } } else { fPage.cannotUpdateSuiteError(); return false; } } catch (JavaModelException e) { e.printStackTrace(); return false; } } } if (finishPage(fPage.getRunnable())) { if (!fPage.hasUpdatedExistingClass()) postCreatingType(); return true; } return false; } protected void postCreatingType() { IType newClass= fPage.getCreatedType(); ICompilationUnit cu= newClass.getCompilationUnit(); if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); //added here } try { IResource resource= cu.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { System.err.println(getClass().getName() + ": " + e); //$NON-NLS-1$ } } public NewTestSuiteCreationWizardPage getPage() { return fPage; } public IRunnableWithProgress getRunnableSave(final IEditorPart cu_ep) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } cu_ep.doSave(monitor); } }; } }
11,866
Bug 11866 Wrong labels in Update Test Suite dialog
"Test Classes to be included" is written with TestClasses (missing space) The status line talks about methods being selected instead of types. The action name is written together (TestSuite) instead of Test Suite
resolved fixed
790bdf0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T12:02:02Z
2002-03-20T16:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestSuiteCreationWizardPage.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.junit.util.*; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; /** * Wizard page to select the test classes to include * in the test suite. */ public class NewTestSuiteCreationWizardPage extends NewTypeWizardPage { private final static String PAGE_NAME= "NewTestSuiteCreationWizardPage"; //$NON-NLS-1$ private final static String CLASSES_IN_SUITE= PAGE_NAME + ".classesinsuite"; //$NON-NLS-1$ private final static String SUITE_NAME= PAGE_NAME + ".suitename"; //$NON-NLS-1$ private final static String SELECTED_CLASSES_LABEL_TEXT_ONE= " class selected."; //$NON-NLS-1$ private final static String SELECTED_CLASSES_LABEL_TEXT_MANY= " classes selected."; //$NON-NLS-1$ private IPackageFragment fCurrentPackage; private CheckboxTableViewer fClassesInSuiteTable; private Button fSelectAllButton; private Button fDeselectAllButton; private Label fSelectedClassesLabel; private Label fSuiteNameLabel; private Text fSuiteNameText; private String fSuiteNameTextInitialValue; private boolean fUpdatedExistingClassButton; public static final String startMarker= "//$JUnit-BEGIN$"; //$NON-NLS-1$ public static final String endMarker= "//$JUnit-END$"; //$NON-NLS-1$ protected IStatus fClassesInSuiteStatus; protected IStatus fSuiteNameStatus; public NewTestSuiteCreationWizardPage() { super(true, PAGE_NAME); fSuiteNameStatus= new JUnitStatus(); fSuiteNameTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestSuiteWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestSuiteWizPage.description")); //$NON-NLS-1$ fClassesInSuiteStatus= new JUnitStatus(); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createSuiteNameControl(composite, nColumns); setTypeName("AllTests",true); //$NON-NLS-1$ createSeparator(composite, nColumns); createClassesInSuiteControl(composite, nColumns); setFocus(); setControl(composite); } /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); updateStatus(findMostSevereStatus()); } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return NewTestCaseCreationWizardPage.getMostSevere(new IStatus[] { fContainerStatus, fPackageStatus, fSuiteNameStatus, fClassesInSuiteStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); updateClassesInSuiteTable(); } else if (fieldName.equals(CLASSES_IN_SUITE)) { fClassesInSuiteStatus= classesInSuiteChanged(); updateSelectedClassesLabel(); } else if (fieldName.equals(SUITE_NAME)) { fSuiteNameStatus= testSuiteChanged(); } updateStatus(findMostSevereStatus()); } public void setVisible(boolean visible) { super.setVisible(visible); updateClassesInSuiteTable(); } protected void updateClassesInSuiteTable() { if (fClassesInSuiteTable != null) { IPackageFragment pack= getPackageFragment(); if (pack == null) { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) pack= root.getPackageFragment(""); //$NON-NLS-1$ else return; } fCurrentPackage= pack; fClassesInSuiteTable.setInput(pack); fClassesInSuiteTable.setAllChecked(true); updateSelectedClassesLabel(); } } protected void createClassesInSuiteControl(Composite parent, int nColumns) { if (fClassesInSuiteTable == null) { Label label = new Label(parent, SWT.LEFT); label.setText(Messages.getString("NewTestSuiteWizPage.classes_in_suite.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalAlignment = GridData.FILL; gd.horizontalSpan = nColumns; label.setLayoutData(gd); fClassesInSuiteTable= CheckboxTableViewer.newCheckList(parent, SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= 200; gd.horizontalSpan= nColumns-1; fClassesInSuiteTable.getTable().setLayoutData(gd); fClassesInSuiteTable.setContentProvider(new ClassesInSuitContentProvider()); fClassesInSuiteTable.setLabelProvider(new JavaElementLabelProvider()); fClassesInSuiteTable.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { handleFieldChanged(CLASSES_IN_SUITE); } }); Composite buttonContainer= new Composite(parent, SWT.NONE); gd= new GridData(GridData.FILL_VERTICAL); buttonContainer.setLayoutData(gd); GridLayout buttonLayout= new GridLayout(); buttonLayout.marginWidth= 0; buttonLayout.marginHeight= 0; buttonContainer.setLayout(buttonLayout); fSelectAllButton= new Button(buttonContainer, SWT.PUSH); fSelectAllButton.setText(Messages.getString("NewTestSuiteWizPage.selectAll")); //$NON-NLS-1$ GridData bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fSelectAllButton.setLayoutData(bgd); fSelectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fClassesInSuiteTable.setAllChecked(true); handleFieldChanged(CLASSES_IN_SUITE); } }); fDeselectAllButton= new Button(buttonContainer, SWT.PUSH); fDeselectAllButton.setText(Messages.getString("NewTestSuiteWizPage.deselectAll")); //$NON-NLS-1$ bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fDeselectAllButton.setLayoutData(bgd); fDeselectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fClassesInSuiteTable.setAllChecked(false); handleFieldChanged(CLASSES_IN_SUITE); } }); // No of selected classes label fSelectedClassesLabel= new Label(parent, SWT.LEFT | SWT.WRAP); fSelectedClassesLabel.setFont(parent.getFont()); updateSelectedClassesLabel(); gd = new GridData(); gd.horizontalSpan = 2; fSelectedClassesLabel.setLayoutData(gd); } } public static class ClassesInSuitContentProvider implements IStructuredContentProvider { private Object[] fTypes; public ClassesInSuitContentProvider() { super(); } public Object[] getElements(Object parent) { try { if (parent instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) parent; ICompilationUnit[] cuArray= pack.getCompilationUnits(); ArrayList typesArrayList= new ArrayList(); for (int i= 0; i < cuArray.length; i++) { ICompilationUnit cu= cuArray[i]; IType[] types= cu.getTypes(); for (int j= 0; j < types.length; j++) { if (TestSearchEngine.isTestImplementor(types[j])) typesArrayList.add(types[j]); } } return typesArrayList.toArray(); } } catch (JavaModelException e) { e.printStackTrace(); } return new Object[0]; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { writeImports(imports); type.createMethod(getSuiteMethodString(), null, false, null); } public String getSuiteMethodString() throws JavaModelException { IPackageFragment pack= getPackageFragment(); String packName= pack.getElementName(); StringBuffer suite= new StringBuffer("public static Test suite () {TestSuite suite= new TestSuite(\"Test for "+((packName.equals(""))?"default package":packName)+"\");\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ suite.append(getUpdatableString()); suite.append("\nreturn suite;}"); //$NON-NLS-1$ return suite.toString(); } public String getUpdatableString() throws JavaModelException { StringBuffer suite= new StringBuffer(); suite.append(startMarker+"\n"); //$NON-NLS-1$ Object[] checkedObjects= fClassesInSuiteTable.getCheckedElements(); for (int i= 0; i < checkedObjects.length; i++) { if (checkedObjects[i] instanceof IType) { IType testType= (IType) checkedObjects[i]; IMethod suiteMethod= testType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (!suiteMethod.exists()) { suite.append("suite.addTest(new TestSuite("+testType.getElementName()+".class));"); //$NON-NLS-1$ //$NON-NLS-2$ } else { suite.append("suite.addTest("+testType.getElementName()+".suite());"); //$NON-NLS-1$ //$NON-NLS-2$ } } } suite.append("\n"+endMarker); //$NON-NLS-1$ return suite.toString(); } public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } updateExistingClass(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } protected void updateExistingClass(IProgressMonitor monitor) throws CoreException, InterruptedException { try { IPackageFragment pack= getPackageFragment(); ICompilationUnit cu= pack.getCompilationUnit(getTypeName() + ".java"); //$NON-NLS-1$ if (!cu.exists()) { createType(monitor); fUpdatedExistingClassButton= false; return; } IType suiteType= cu.getType(getTypeName()); monitor.beginTask(Messages.getString("NewTestSuiteWizPage.createType.beginTask"), 10); //$NON-NLS-1$ IMethod suiteMethod= suiteType.getMethod("suite", new String[] {}); //$NON-NLS-1$ monitor.worked(1); String lineDelimiter= JUnitStubUtility.getLineDelimiterUsed(cu); if (suiteMethod.exists()) { ISourceRange range= suiteMethod.getSourceRange(); if (range != null) { IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); StringBuffer source= new StringBuffer(originalContent); //using JDK 1.4 //int start= source.toString().indexOf(startMarker) --> int start= source.indexOf(startMarker); int start= source.toString().indexOf(startMarker); if (start > -1) { //using JDK 1.4 //int end= source.toString().indexOf(endMarker, start) --> int end= source.indexOf(endMarker, start) int end= source.toString().indexOf(endMarker, start); if (end > -1) { monitor.subTask(Messages.getString("NewTestSuiteWizPage.createType.updating.suite_method")); //$NON-NLS-1$ monitor.worked(1); end += endMarker.length(); source.replace(start, end, getUpdatableString()); buf.replace(range.getOffset(), range.getLength(), source.toString()); cu.reconcile(); originalContent= buf.getText(0, buf.getLength()); monitor.worked(1); String formattedContent= JUnitStubUtility.codeFormat(originalContent, 0, lineDelimiter); buf.replace(0, buf.getLength(), formattedContent); monitor.worked(1); cu.save(new SubProgressMonitor(monitor, 1), false); } else { cannotUpdateSuiteError(); } } else { cannotUpdateSuiteError(); } } else { MessageDialog.openError(getShell(), Messages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.title"), Messages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.message")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { suiteType.createMethod(getSuiteMethodString(), null, true, monitor); ISourceRange range= cu.getSourceRange(); IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); monitor.worked(2); String formattedContent= JUnitStubUtility.codeFormat(originalContent, 0, lineDelimiter); buf.replace(range.getOffset(), range.getLength(), formattedContent); monitor.worked(1); cu.save(new SubProgressMonitor(monitor, 1), false); } monitor.done(); fUpdatedExistingClassButton= true; } catch (JavaModelException e) { e.printStackTrace(); } } public boolean hasUpdatedExistingClass() { return fUpdatedExistingClassButton; } private IStatus classesInSuiteChanged() { JUnitStatus status= new JUnitStatus(); if (fClassesInSuiteTable.getCheckedElements().length <= 0) status.setWarning(Messages.getString("NewTestSuiteWizPage.classes_in_suite.error.no_testclasses_selected")); //$NON-NLS-1$ return status; } private void updateSelectedClassesLabel() { int noOfClassesChecked= fClassesInSuiteTable.getCheckedElements().length; fSelectedClassesLabel.setText(noOfClassesChecked+((noOfClassesChecked==1)?SELECTED_CLASSES_LABEL_TEXT_ONE:SELECTED_CLASSES_LABEL_TEXT_MANY)); } protected void createSuiteNameControl(Composite composite, int nColumns) { fSuiteNameLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fSuiteNameLabel.setFont(composite.getFont()); fSuiteNameLabel.setText(Messages.getString("NewTestSuiteWizPage.suiteName.text")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fSuiteNameLabel.setLayoutData(gd); fSuiteNameText= new Text(composite, SWT.SINGLE | SWT.BORDER); // moved up due to 1GEUNW2 fSuiteNameText.setEnabled(true); fSuiteNameText.setFont(composite.getFont()); fSuiteNameText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(SUITE_NAME); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fSuiteNameText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fSuiteNameText==null)?fSuiteNameTextInitialValue:fSuiteNameText.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { if (fSuiteNameText == null) { fSuiteNameTextInitialValue= name; } else { fSuiteNameText.setText(name); fSuiteNameText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testSuiteChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestSuiteWizPage.typeName.error.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestSuiteWizPage.typeName.error.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestSuiteWizPage.typeName.error.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestSuiteWizPage.typeName.error.name.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setWarning(Messages.getString("NewTestSuiteWizPage.typeName.warning.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * Sets the focus. */ protected void setFocus() { fSuiteNameText.setFocus(); } public void setCheckedElements(Object[] elements) { fClassesInSuiteTable.setCheckedElements(elements); } protected void cannotUpdateSuiteError() { MessageDialog.openError(getShell(), Messages.getString("NewTestSuiteWizPage.cannotUpdateDialog.title"), //$NON-NLS-1$ Messages.getFormattedString("NewTestSuiteWizPage.cannotUpdateDialog.message", new String[] {startMarker, endMarker})); //$NON-NLS-1$ } private void writeImports(IImportsStructure imports) { imports.addImport("junit.framework.Test"); //$NON-NLS-1$ imports.addImport("junit.framework.TestSuite"); //$NON-NLS-1$ } // /** // * Creates a type using the current field values. // */ // public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { // monitor.beginTask(Messages.getString("NewTestSuiteWizPage.createType.beginTask"), 10); //$NON-NLS-1$ // // IPackageFragmentRoot root= getPackageFragmentRoot(); // IPackageFragment pack= getPackageFragment(); // if (pack == null) { // pack= root.getPackageFragment(""); //$NON-NLS-1$ // } // // if (!pack.exists()) { // String packName= pack.getElementName(); // pack= root.createPackageFragment(packName, true, null); // } // // monitor.worked(1); // // String clName= getTypeName(); // // boolean isInnerClass= isEnclosingTypeSelected(); // // IType createdType; // ImportsStructure imports; // int indent= 0; // // String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); // int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); // // String lineDelimiter= null; // // ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$ // // imports= new ImportsStructure(parentCU, prefOrder, threshold, false); // // lineDelimiter= JUnitStubUtility.getLineDelimiterUsed(parentCU); // // String content= createTypeBody(imports, lineDelimiter, parentCU); // createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5)); // // // add imports for superclass/interfaces, so the type can be parsed correctly //// writeImports(imports); // imports.create(true, new SubProgressMonitor(monitor, 1)); // // String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1)); // if (methods.length > 0) { // for (int i= 0; i < methods.length; i++) { // createdType.createMethod(methods[i], null, false, null); // } // // add imports // imports.create(!isInnerClass, null); // } // monitor.worked(1); // // ICompilationUnit cu= createdType.getCompilationUnit(); // ISourceRange range; // if (isInnerClass) { // synchronized(cu) { // cu.reconcile(); // } // range= createdType.getSourceRange(); // } else { // range= cu.getSourceRange(); // } // // IBuffer buf= cu.getBuffer(); // String originalContent= buf.getText(range.getOffset(), range.getLength()); // String formattedContent= JUnitStubUtility.codeFormat(originalContent, indent, lineDelimiter); // buf.replace(range.getOffset(), range.getLength(), formattedContent); // if (!isInnerClass) { // String fileComment= getFileComment(cu); // if (fileComment != null) { // buf.replace(0, 0, fileComment + lineDelimiter); // } // buf.save(new SubProgressMonitor(monitor, 1), false); // } else { // monitor.worked(1); // } // fCreatedType= createdType; // monitor.done(); // } // // /* // * Called from createType to construct the source for this type // */ // private String createTypeBody(IImportsStructure imports, String lineDelimiter, ICompilationUnit parentCU) { // StringBuffer buf= new StringBuffer(); // String typeComment= getTypeComment(parentCU); // if (typeComment != null) { // buf.append(typeComment); // buf.append(lineDelimiter); // } // // int modifiers= getModifiers(); // buf.append(Flags.toString(modifiers)); // if (modifiers != 0) { // buf.append(' '); // } // buf.append("class "); //$NON-NLS-1$ // buf.append(getTypeName()); // buf.append(" {"); //$NON-NLS-1$ // buf.append(lineDelimiter); // buf.append(lineDelimiter); // buf.append('}'); // buf.append(lineDelimiter); // return buf.toString(); // } // // public IType getCreatedType() { // return fCreatedType; // } }
11,866
Bug 11866 Wrong labels in Update Test Suite dialog
"Test Classes to be included" is written with TestClasses (missing space) The status line talks about methods being selected instead of types. The action name is written together (TestSuite) instead of Test Suite
resolved fixed
790bdf0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T12:02:02Z
2002-03-20T16:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/UpdateTestSuite.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.*; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; /** * An object contribution action that updates existing AllTests classes. */ public class UpdateTestSuite implements IObjectActionDelegate { private Shell fShell; private IPackageFragment fPack; private ICompilationUnit fTestSuite; private IMethod fSuiteMethod; private static boolean fEmptySelectionAllowed= false; private Object[] fSelectedTestCases; private class UpdateAllTestsValidator implements ISelectionValidator { /* * @see ISelectionValidator#validate(Object[]) */ public IStatus validate(Object[] selection) { int count= 0; for (int i= 0; i < selection.length; i++) { if (selection[i] instanceof IType) { count++; } } if (count == 0 && !fEmptySelectionAllowed) { return new JUnitStatus(IStatus.ERROR, ""); //$NON-NLS-1$ } String message; if (count == 1) { message= Messages.getFormattedString("UpdateAllTests.selected_methods.label_one", new Integer(count)); //$NON-NLS-1$ } else { message= Messages.getFormattedString("UpdateAllTests.selected_methods.label_many", new Integer(count)); //$NON-NLS-1$ } return new JUnitStatus(IStatus.INFO, message); } } public UpdateTestSuite() { super(); } /* * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { } /* * @see IActionDelegate#run(IAction) */ public void run(IAction action) { ILabelProvider lprovider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); IStructuredContentProvider cprovider= new NewTestSuiteCreationWizardPage.ClassesInSuitContentProvider(); /* find TestClasses already in Test Suite */ IType testSuiteType= JavaModelUtil.findPrimaryType(fTestSuite); fSuiteMethod= testSuiteType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (fSuiteMethod.exists()) { try { ISourceRange range= fSuiteMethod.getSourceRange(); IBuffer buf= fTestSuite.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); buf.close(); int start= originalContent.indexOf(NewTestSuiteCreationWizardPage.startMarker); if (start > -1) { if (originalContent.indexOf(NewTestSuiteCreationWizardPage.endMarker, start) > -1) { CheckedTableSelectionDialog dialog= new CheckedTableSelectionDialog(fShell, lprovider, cprovider); dialog.setValidator(new UpdateAllTestsValidator()); dialog.setTitle(Messages.getString("UpdateAllTests.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("UpdateAllTests.message")); //$NON-NLS-1$ dialog.setInitialSelections(cprovider.getElements(fPack)); dialog.setSize(60, 25); dialog.setInput(fPack); if (dialog.open() == dialog.OK) { fSelectedTestCases= dialog.getResult(); ProgressMonitorDialog progressDialog= new ProgressMonitorDialog(fShell); try { progressDialog.run(false, false, getRunnable()); } catch (Exception e) { e.printStackTrace(); } } } else { cannotUpdateSuiteError(); } } else { cannotUpdateSuiteError(); } } catch (JavaModelException e) { e.printStackTrace(); } } else { noSuiteError(); } } /* * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { fShell= JUnitPlugin.getActiveWorkbenchShell(); if (selection instanceof IStructuredSelection) { Object testSuiteObj= ((IStructuredSelection) selection).getFirstElement(); if (testSuiteObj != null && testSuiteObj instanceof ICompilationUnit) { fTestSuite= (ICompilationUnit) testSuiteObj; IJavaElement packIJE= fTestSuite.getParent(); if (packIJE instanceof IPackageFragment) { fPack= (IPackageFragment) packIJE; } } } } private void updateTestCasesInSuite(IProgressMonitor monitor) { try { monitor.beginTask(Messages.getString("UpdateAllTests.beginTask"), 5); //$NON-NLS-1$ ISourceRange range= fSuiteMethod.getSourceRange(); IBuffer buf= fTestSuite.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); StringBuffer source= new StringBuffer(originalContent); //using JDK 1.4 //int start= source.toString().indexOf(NewTestSuiteCreationWizardPage.startMarker) --> int start= source.indexOf(NewTestSuiteCreationWizardPage.startMarker) int start= source.toString().indexOf(NewTestSuiteCreationWizardPage.startMarker); if (start > -1) { //using JDK 1.4 //int end= source.toString().indexOf(NewTestSuiteCreationWizardPage.endMarker, start) --> int end= source.indexOf(NewTestSuiteCreationWizardPage.endMarker, start) int end= source.toString().indexOf(NewTestSuiteCreationWizardPage.endMarker, start); if (end > -1) { monitor.worked(1); end += NewTestSuiteCreationWizardPage.endMarker.length(); // String updatableCode= source.substring(start,end+NewTestSuiteCreationWizardPage.endMarker.length()); source.replace(start, end, getUpdatableString()); buf.replace(range.getOffset(), range.getLength(), source.toString()); monitor.worked(1); fTestSuite.reconcile(); originalContent= buf.getText(0, buf.getLength()); monitor.worked(1); String formattedContent= JUnitStubUtility.codeFormat( originalContent, 0, JUnitStubUtility.getLineDelimiterUsed(fTestSuite)); //buf.replace(range.getOffset(), range.getLength(), formattedContent); buf.replace(0, buf.getLength(), formattedContent); monitor.worked(1); fTestSuite.save(new SubProgressMonitor(monitor, 1), true); } } } catch (JavaModelException e) { e.printStackTrace(); } } public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } updateTestCasesInSuite(monitor); } }; } public String getUpdatableString() throws JavaModelException { StringBuffer suite= new StringBuffer(); suite.append(NewTestSuiteCreationWizardPage.startMarker+"\n"); //$NON-NLS-1$ for (int i= 0; i < fSelectedTestCases.length; i++) { if (fSelectedTestCases[i] instanceof IType) { IType testType= (IType) fSelectedTestCases[i]; IMethod suiteMethod= testType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (!suiteMethod.exists()) { suite.append("suite.addTest(new TestSuite("+testType.getElementName()+".class));"); //$NON-NLS-1$ //$NON-NLS-2$ } else { suite.append("suite.addTest("+testType.getElementName()+".suite());"); //$NON-NLS-1$ //$NON-NLS-2$ } } } suite.append("\n"+NewTestSuiteCreationWizardPage.endMarker); //$NON-NLS-1$ return suite.toString(); } private void cannotUpdateSuiteError() { MessageDialog.openError(fShell, Messages.getString("UpdateAllTests.cannotUpdate.errorDialog.title"), //$NON-NLS-1$ Messages.getFormattedString("UpdateAllTests.cannotUpdate.errorDialog.message", new String[] {NewTestSuiteCreationWizardPage.startMarker, NewTestSuiteCreationWizardPage.endMarker})); //$NON-NLS-1$ } private void noSuiteError() { MessageDialog.openError(fShell, Messages.getString("UpdateAllTests.cannotFind.errorDialog.title"), Messages.getString("UpdateAllTests.cannotFind.errorDialog.message")); } }
11,863
Bug 11863 Update Test Suite action does not allow to remove
What the action actually does is RECREATE the test suite based on the selection in the dialog. I do an update on a test suite which contains X. It is no clear that if I only select Y in the dialog that I'll end up with X being removed. Normally "Update" shows the content of the existing stuff (dir, zip) and allows to modify this. I think renaming the action (and the dialog) to Recreate Test Suite would solve the problem.
resolved fixed
7b3c35c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T12:54:45Z
2002-03-20T16:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizard.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; /** * A wizard for creating test cases. */ public class NewTestCaseCreationWizard extends JUnitWizard { private NewTestCaseCreationWizardPage fPage; private NewTestCaseCreationWizardPage2 fPage2; public NewTestCaseCreationWizard() { super(); //setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS); //setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle("JUnit TestCase"); } /* * @see Wizard#createPages */ public void addPages() { super.addPages(); IWorkspace workspace= ResourcesPlugin.getWorkspace(); fPage= new NewTestCaseCreationWizardPage(); fPage2= new NewTestCaseCreationWizardPage2(fPage); addPage(fPage); fPage.init(getSelection(),fPage2); addPage(fPage2); } /* * @see Wizard#performFinish */ public boolean performFinish() { if (finishPage(fPage.getRunnable())) { IType newClass= fPage.getCreatedType(); ICompilationUnit cu= newClass.getCompilationUnit(); if (cu.isWorkingCopy()) { cu= (ICompilationUnit)cu.getOriginalElement(); //added here } try { IResource resource= cu.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { // let pass, only reveal and open will fail JUnitPlugin.log(e); } return true; } return false; } }
11,863
Bug 11863 Update Test Suite action does not allow to remove
What the action actually does is RECREATE the test suite based on the selection in the dialog. I do an update on a test suite which contains X. It is no clear that if I only select Y in the dialog that I'll end up with X being removed. Normally "Update" shows the content of the existing stuff (dir, zip) and allows to modify this. I think renaming the action (and the dialog) to Recreate Test Suite would solve the problem.
resolved fixed
7b3c35c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T12:54:45Z
2002-03-20T16:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); updateStatus(findMostSevereStatus()); // put default class to test if (element != null) { IType enclosingType= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { enclosingType= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) enclosingType= JavaModelUtil.findPrimaryType(cu); } if (enclosingType != null) { try { if (!TestSearchEngine.isTestImplementor(enclosingType)) { fDefaultClassToTest= enclosingType.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return NewTestCaseCreationWizardPage.getMostSevere(new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } updateStatus(findMostSevereStatus()); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); setFocus(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. * @param canBeModified Selects if the super class can be changed by the user */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type) throws JavaModelException { String constr= "public "+getTypeName()+"(String name) {super(name);}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(constr, null, false, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp; IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { setUp="/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown; IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start)) start++; else if (param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) { start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } if (newMethodsNames.contains(methodName.toString())) methodName.append("1"); //$NON-NLS-1$ newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } protected static GridData gridDataForDefaultForTypeName(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } public static Control createEmptySpace(Composite parent, int span) { Label label= new Label(parent, SWT.LEFT); GridData gd= new GridData(); gd.horizontalAlignment= gd.BEGINNING; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= span; gd.horizontalIndent= 0; gd.widthHint= 0; gd.heightHint= 0; label.setLayoutData(gd); return label; } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists fFirstTime= false; } } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see WizardPage#getNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); if (!val.isOK()) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ return status; } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.interface_not_visible",classToTestName));//$NON-NLS-1$ return status; } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Finds the most severe status from a array of stati. * An error is more severe than a warning, and a warning is more severe * than ok. */ public static IStatus getMostSevere(IStatus[] status) { IStatus max= null; for (int i= 0; i < status.length; i++) { IStatus curr= status[i]; if (curr.matches(IStatus.ERROR)) { return curr; } if (max == null || curr.getSeverity() > max.getSeverity()) { max= curr; } } return max; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); } }
11,844
Bug 11844 new TestCase does not store settings
All checkboxes are not persisted
resolved fixed
3a0f07f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T15:01:27Z
2002-03-20T13:13:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizard.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; /** * A wizard for creating test cases. */ public class NewTestCaseCreationWizard extends JUnitWizard { private NewTestCaseCreationWizardPage fPage; private NewTestCaseCreationWizardPage2 fPage2; public NewTestCaseCreationWizard() { super(); //setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS); //setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle("JUnit TestCase"); } /* * @see Wizard#createPages */ public void addPages() { super.addPages(); IWorkspace workspace= ResourcesPlugin.getWorkspace(); fPage= new NewTestCaseCreationWizardPage(); fPage2= new NewTestCaseCreationWizardPage2(fPage); addPage(fPage); fPage.init(getSelection(),fPage2); addPage(fPage2); } /* * @see Wizard#performFinish */ public boolean performFinish() { if (finishPage(fPage.getRunnable())) { IType newClass= fPage.getCreatedType(); ICompilationUnit cu= newClass.getCompilationUnit(); if (cu.isWorkingCopy()) { cu= (ICompilationUnit)cu.getOriginalElement(); } try { IResource resource= cu.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { JUnitPlugin.log(e); // let pass, only reveal and open will fail } return true; } return false; } }
11,844
Bug 11844 new TestCase does not store settings
All checkboxes are not persisted
resolved fixed
3a0f07f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T15:01:27Z
2002-03-20T13:13:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); updateStatus(findMostSevereStatus()); // put default class to test if (element != null) { IType enclosingType= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { enclosingType= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) enclosingType= JavaModelUtil.findPrimaryType(cu); } if (enclosingType != null) { try { if (!TestSearchEngine.isTestImplementor(enclosingType)) { fDefaultClassToTest= enclosingType.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return NewTestCaseCreationWizardPage.getMostSevere(new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } updateStatus(findMostSevereStatus()); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); setFocus(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. * @param canBeModified Selects if the super class can be changed by the user */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type) throws JavaModelException { String constr= "public "+getTypeName()+"(String name) {super(name);}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(constr, null, false, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp; IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { setUp="/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown; IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start) || param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } if (newMethodsNames.contains(methodName.toString())) methodName.append("1"); //$NON-NLS-1$ newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } protected static GridData gridDataForDefaultForTypeName(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } public static Control createEmptySpace(Composite parent, int span) { Label label= new Label(parent, SWT.LEFT); GridData gd= new GridData(); gd.horizontalAlignment= gd.BEGINNING; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= span; gd.horizontalIndent= 0; gd.widthHint= 0; gd.heightHint= 0; label.setLayoutData(gd); return label; } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists fFirstTime= false; } } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see WizardPage#getNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); if (!val.isOK()) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ return status; } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.interface_not_visible",classToTestName));//$NON-NLS-1$ return status; } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Finds the most severe status from a array of stati. * An error is more severe than a warning, and a warning is more severe * than ok. */ public static IStatus getMostSevere(IStatus[] status) { IStatus max= null; for (int i= 0; i < status.length; i++) { IStatus curr= status[i]; if (curr.matches(IStatus.ERROR)) { return curr; } if (max == null || curr.getSeverity() > max.getSeverity()) { max= curr; } } return max; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); } }
11,844
Bug 11844 new TestCase does not store settings
All checkboxes are not persisted
resolved fixed
3a0f07f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T15:01:27Z
2002-03-20T13:13:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/SelectionButtonGroup.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import org.eclipse.jdt.internal.junit.util.*; import org.eclipse.jface.util.Assert; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; /** * A group of controls used in the JUnit TestCase wizard. */ public class SelectionButtonGroup { private Label fLabel; protected String fLabelText; private SelectionButtonGroupListener fGroupListener; private boolean fEnabled; private Composite fButtonComposite; private Button[] fButtons; private String[] fButtonNames; private boolean[] fButtonsSelected; private boolean[] fButtonsEnabled; private Combo fMainCombo; private boolean fMainComboEnabled; private int fGroupBorderStyle; private int fGroupNumberOfColumns; private int fButtonsStyle; public interface SelectionButtonGroupListener { /** * The dialog field has changed. */ void groupChanged(SelectionButtonGroup field); } /** * Creates a group without border. */ public SelectionButtonGroup(int buttonsStyle, String[] buttonNames, int nColumns) { this(buttonsStyle, buttonNames, nColumns, SWT.NONE); } /** * Creates a group with border (label in border). * Accepted button styles are: SWT.RADIO, SWT.CHECK, SWT.TOGGLE * For border styles see <code>Group</code> */ public SelectionButtonGroup(int buttonsStyle, String[] buttonNames, int nColumns, int borderStyle) { fEnabled= true; fLabel= null; fLabelText= ""; //$NON-NLS-1$ Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE); fButtonNames= buttonNames; int nButtons= buttonNames.length; fButtonsSelected= new boolean[nButtons]; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsSelected[i]= false; fButtonsEnabled[i]= true; } fMainComboEnabled= true; if (fButtonsStyle == SWT.RADIO) { fButtonsSelected[0]= true; } fGroupBorderStyle= borderStyle; fGroupNumberOfColumns= (nColumns <= 0) ? nButtons : nColumns; fButtonsStyle= buttonsStyle; } /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); if (fGroupBorderStyle == SWT.NONE) { Label label= getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); Composite buttonsgroup= getSelectionButtonsGroup(parent); GridData gd= new GridData(); gd.horizontalSpan= nColumns - 1; buttonsgroup.setLayoutData(gd); return new Control[] { label, buttonsgroup }; } else { Composite buttonsgroup= getSelectionButtonsGroup(parent); GridData gd= new GridData(); gd.horizontalSpan= nColumns; buttonsgroup.setLayoutData(gd); return new Control[] { buttonsgroup }; } } /* * @see DialogField#doFillIntoGrid */ public int getNumberOfControls() { return (fGroupBorderStyle == SWT.NONE) ? 2 : 1; } private Button createSelectionButton(int index, Composite group, SelectionListener listener) { Button button= new Button(group, fButtonsStyle | SWT.LEFT); button.setFont(group.getFont()); button.setText(fButtonNames[index]); button.setEnabled(isEnabled() && fButtonsEnabled[index]); button.setSelection(fButtonsSelected[index]); button.addSelectionListener(listener); button.setLayoutData(new GridData()); return button; } private Button createMainCombo(int index, Composite group, SelectionListener listener) { Composite buttonComboGroup= new Composite(group, 0); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 20; layout.numColumns= 2; buttonComboGroup.setLayout(layout); Button button= new Button(buttonComboGroup, fButtonsStyle | SWT.LEFT); button.setFont(group.getFont()); button.setText(fButtonNames[index]); button.setEnabled(isEnabled() && fButtonsEnabled[index]); button.setSelection(fButtonsSelected[index]); button.addSelectionListener(listener); button.setLayoutData(new GridData()); fMainCombo= new Combo(buttonComboGroup, SWT.READ_ONLY); fMainCombo.setItems(new String[] {"text ui","swing ui","awt ui"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ fMainCombo.select(0); fMainCombo.setEnabled(isEnabled() && fMainComboEnabled); fMainCombo.setFont(group.getFont()); fMainCombo.setLayoutData(new GridData()); return button; } /** * Returns the group widget. When called the first time, the widget will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getSelectionButtonsGroup(Composite parent) { if (fButtonComposite == null) { assertCompositeNotNull(parent); GridLayout layout= new GridLayout(); layout.makeColumnsEqualWidth= true; layout.numColumns= fGroupNumberOfColumns; if (fGroupBorderStyle != SWT.NONE) { Group group= new Group(parent, fGroupBorderStyle); if (fLabelText != null && fLabelText.length() > 0) { group.setText(fLabelText); } fButtonComposite= group; } else { fButtonComposite= new Composite(parent, SWT.NULL); layout.marginHeight= 0; layout.marginWidth= 0; } fButtonComposite.setLayout(layout); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doWidgetSelected(e); } public void widgetSelected(SelectionEvent e) { doWidgetSelected(e); } }; int nButtons= fButtonNames.length; fButtons= new Button[nButtons]; fButtons[0]= createSelectionButton(0, fButtonComposite, listener); fButtons[1]= createMainCombo(1, fButtonComposite, listener); for (int i= 2; i < nButtons; i++) { fButtons[i]= createSelectionButton(i, fButtonComposite, listener); } int nRows= nButtons / fGroupNumberOfColumns; int nFillElements= nRows * fGroupNumberOfColumns - nButtons; for (int i= 0; i < nFillElements; i++) { createEmptySpace(fButtonComposite); } } return fButtonComposite; } /** * Returns a button from the group or <code>null</code> if not yet created. */ public Button getSelectionButton(int index) { if (index >= 0 && index < fButtons.length) { return fButtons[index]; } return null; } private void doWidgetSelected(SelectionEvent e) { Button button= (Button)e.widget; for (int i= 0; i < fButtons.length; i++) { if (fButtons[i] == button) { fButtonsSelected[i]= button.getSelection(); dialogFieldChanged(); return; } } } /** * Returns the selection state of a button contained in the group. * @param The index of the button */ public boolean isSelected(int index) { if (index >= 0 && index < fButtonsSelected.length) { return fButtonsSelected[index]; } return false; } /** * Sets the selection state of a button contained in the group. */ public void setSelection(int index, boolean selected) { if (index >= 0 && index < fButtonsSelected.length) { if (fButtonsSelected[index] != selected) { fButtonsSelected[index]= selected; if (fButtons != null) { Button button= fButtons[index]; if (isOkToUse(button)) { button.setSelection(selected); } } } } } /** * Returns the enabled state of a button contained in the group. * @param The index of the button */ public boolean isEnabled(int index) { if (index >= 0 && index < fButtonsEnabled.length) { return fButtonsEnabled[index]; } return false; } /** * Sets the selection state of a button contained in the group. */ public void setEnabled(int index, boolean enabled) { if (index >= 0 && index < fButtonsEnabled.length) { if (fButtonsEnabled[index] != enabled) { fButtonsEnabled[index]= enabled; if (index == 1) fMainComboEnabled= enabled; if (fButtons != null) { Button button= fButtons[index]; if (isOkToUse(button)) { button.setEnabled(enabled); if (index == 1) fMainCombo.setEnabled(enabled); } } } } } protected void updateEnableState() { if (fLabel != null) { fLabel.setEnabled(fEnabled); } if (fButtons != null) { boolean enabled= isEnabled(); for (int i= 0; i < fButtons.length; i++) { Button button= fButtons[i]; if (isOkToUse(button)) { button.setEnabled(enabled && fButtonsEnabled[i]); } } fMainCombo.setEnabled(enabled && fMainComboEnabled); } } public int getComboSelection() { return fMainCombo.getSelectionIndex(); } /** * Sets the label of the dialog field. */ public void setLabelText(String labeltext) { fLabelText= labeltext; } /** * Defines the listener for this dialog field. */ public final void setSelectionGroupListener(SelectionButtonGroupListener listener) { fGroupListener= listener; } /** * Programatical invocation of a dialog field change. */ public void dialogFieldChanged() { if (fGroupListener != null) { fGroupListener.groupChanged(this); } } /** * Tries to set the focus to the dialog field. * Returns <code>true</code> if the dialog field can take focus. * To be reimplemented by dialog field implementors. */ public boolean setFocus() { return false; } /** * Posts <code>setFocus</code> to the display event queue. */ public void postSetFocusOnDialogField(Display display) { if (display != null) { display.asyncExec( new Runnable() { public void run() { setFocus(); } } ); } } protected static GridData gridDataForLabel(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } /** * Creates or returns the created label widget. * @param parent The parent composite or <code>null</code> if the widget has * already been created. */ public Label getLabelControl(Composite parent) { if (fLabel == null) { assertCompositeNotNull(parent); fLabel= new Label(parent, SWT.LEFT | SWT.WRAP); fLabel.setFont(parent.getFont()); fLabel.setEnabled(fEnabled); if (fLabelText != null && !"".equals(fLabelText)) { //$NON-NLS-1$ fLabel.setText(fLabelText); } else { // XXX: to avoid a 16 pixel wide empty label - revisit fLabel.setText("."); //$NON-NLS-1$ fLabel.setVisible(false); } } return fLabel; } /** * Creates a spacer control. * @param parent The parent composite */ public static Control createEmptySpace(Composite parent) { return createEmptySpace(parent, 1); } /** * Creates a spacer control with the given span. * The composite is assumed to have <code>MGridLayout</code> as * layout. * @param parent The parent composite */ public static Control createEmptySpace(Composite parent, int span) { return LayoutUtil.createEmptySpace(parent, span); } /** * Tests is the control is not <code>null</code> and not disposed. */ protected final boolean isOkToUse(Control control) { return (control != null) && !(control.isDisposed()); } // --------- enable / disable management /** * Sets the enable state of the dialog field. */ public final void setEnabled(boolean enabled) { if (enabled != fEnabled) { fEnabled= enabled; updateEnableState(); } } /** * Gets the enable state of the dialog field. */ public final boolean isEnabled() { return fEnabled; } protected final void assertCompositeNotNull(Composite comp) { Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$ } protected final void assertEnoughColumns(int nColumns) { Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$ } }
11,770
Bug 11770 java browsing: multi-selection disabled in 2 of 4 views
multi selection is disabled in the package and type views but it's enabled in project and member views
verified fixed
3839f03
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T15:41:17Z
2002-03-20T10:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import java.util.Collection; import java.util.Comparator; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; 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.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.DecoratingLabelProvider; 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.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; 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.IPartListener; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.NewWizardMenu; import org.eclipse.ui.actions.OpenPerspectiveMenu; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.actions.RefreshAction; import org.eclipse.ui.dialogs.PropertyDialogAction; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.views.internal.framelist.BackAction; import org.eclipse.ui.views.internal.framelist.ForwardAction; import org.eclipse.ui.views.internal.framelist.GoIntoAction; import org.eclipse.ui.views.internal.framelist.UpAction; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.internal.core.JavaElement; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.packageview.BuildGroup; import org.eclipse.jdt.internal.ui.packageview.OpenResourceAction; import org.eclipse.jdt.internal.ui.packageview.PackagesMessages; import org.eclipse.jdt.internal.ui.packageview.ShowInNavigatorAction; import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener { private ILabelProvider fLabelProvider; private ILabelProvider fTitleProvider; private StructuredViewer fViewer; private IMemento fMemento; private JavaElementTypeComparator fTypeComparator; // Actions private ContextMenuGroup[] fStandardGroups; private Menu fContextMenu; private OpenResourceAction fOpenCUAction; private Action fOpenToAction; private Action fShowNavigatorAction; private PropertyDialogAction fPropertyDialogAction; private IRefactoringAction fDeleteAction; private RefreshAction fRefreshAction; private BackAction fBackAction; private ForwardAction fForwardAction; private GoIntoAction fZoomInAction; private UpAction fUpAction; // private GotoTypeAction fGotoTypeAction; // private GotoPackageAction fGotoPackageAction; private IWorkbenchPart fPreviousSelectionProvider; private Image fOriginalTitleImage; /* * Ensure selection changed events being processed only if * initiated by user interaction with this part. */ private boolean fProcessSelectionEvents= true; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { setSelectionFromEditor(part); } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; /* * Implements method from IViewPart. */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } // XXX: need to save state here // fViewer.saveState(memento); } /** * Creates the search list inner viewer. */ public void createPartControl(Composite parent) { Assert.isTrue(fViewer == null); if (fMemento != null) // XXX: Restore state here // fViewer.restoreState(fMemento); fMemento= null; fTypeComparator= new JavaElementTypeComparator(); // Setup viewer fViewer= createViewer(parent); fLabelProvider= createLabelProvider(); ILabelDecorator decorationMgr= PlatformUI.getWorkbench().getDecoratorManager(); fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr)); fViewer.setSorter(new JavaElementSorter()); fViewer.setUseHashlookup(true); JavaPlugin.getDefault().getProblemMarkerManager().addListener((IProblemChangedListener)fViewer); fTitleProvider= createTitleProvider(); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getControl()); fViewer.getControl().setMenu(fContextMenu); getSite().registerContextMenu(menuMgr, fViewer); createActions(); // call before registering for selection changes addKeyListener(); getSite().setSelectionProvider(fViewer); // Status line IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); hookViewerListeners(); // Initialize viewer input fViewer.setContentProvider(createContentProvider()); setInitialInput(); // Initialize selecton setInitialSelection(); // Filters addFilters(); fillToolBar(getViewSite().getActionBars().getToolBarManager()); // Listen to workbench window changes getViewSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this); getViewSite().getPage().addPartListener(fPartListener); setHelp(); } //---- IWorkbenchPart ------------------------------------------------------ public void setFocus() { fViewer.getControl().setFocus(); } public void dispose() { if (fViewer != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener((IProblemChangedListener)fViewer); getViewSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this); getViewSite().getPage().removePartListener(fPartListener); fViewer= null; } super.dispose(); } /** * Adds the KeyListener */ protected void addKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { handleKeyReleased(event); } }); } protected void handleKeyReleased(KeyEvent event) { if (event.stateMask != 0) return; int key= event.keyCode; if (key == SWT.F5) { fRefreshAction.selectionChanged( (IStructuredSelection) fViewer.getSelection()); if (fRefreshAction.isEnabled()) fRefreshAction.run(); } else if (key == SWT.F4) { OpenTypeHierarchyUtil.open(getSelectionProvider().getSelection(), getSite().getWorkbenchWindow()); } else if (key == SWT.F3) { fOpenCUAction.update(); if (fOpenCUAction.isEnabled()) fOpenCUAction.run(); } else if (event.character == SWT.DEL) { fDeleteAction.update(); if (fDeleteAction.isEnabled()) fDeleteAction.run(); } } //---- Adding Action to Toolbar ------------------------------------------- protected void fillToolBar(IToolBarManager tbm) { // fViewer.fillToolBar(tbm); } // protected void setContextMenuContributor(final IContextMenuContributor contributor) { // // Make sure we are doing it in the right thread. // getDisplay().syncExec(new Runnable() { // public void run() { //// getViewer().setContextMenuTarget(contributor); // } // }); // } /** * Called when the context menu is about to open. * Override to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); fPropertyDialogAction.selectionChanged(selection); MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$ menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu); new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false); // updateActions(selection); // Object element= selection.getFirstElement(); // if (selection.size() == 1 && fViewer.isExpandable(element)) // menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction); // addGotoMenu(menu); // // Open menus fOpenCUAction.update(); if (fOpenCUAction.isEnabled()) menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction); addOpenWithMenu(menu, selection); addOpenToMenu(menu, selection); addRefactoring(menu); ContextMenuGroup.add(menu, fStandardGroups, fViewer); menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction); fRefreshAction.selectionChanged(selection); menu.add(new Separator()); if (fPropertyDialogAction.isApplicableForSelection()) menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction); } private void addRefactoring(IMenuManager menu){ MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void createActions() { ISelectionProvider provider= getSelectionProvider(); fOpenCUAction= new OpenResourceAction(provider); fPropertyDialogAction= new PropertyDialogAction(getShell(), provider); fShowNavigatorAction= new ShowInNavigatorAction(provider); fStandardGroups= new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup(), new GenerateGroup(), new JavaSearchGroup() }; fDeleteAction= ReorgGroup.createDeleteAction(provider); fRefreshAction= new RefreshAction(getShell()); // fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$ // fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$ // fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$ // fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$ // fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$ // fBackAction= new BackAction(fFrameList); // fForwardAction= new ForwardAction(fFrameList); // fZoomInAction= new GoIntoAction(fFrameList); // fUpAction= new UpAction(fFrameList); // fGotoTypeAction= new GotoTypeAction(this); // fGotoPackageAction= new GotoPackageAction(this); IActionBars actionService= getViewSite().getActionBars(); actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction); ReorgGroup.addGlobalReorgActions(actionService, provider); } private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) { if (selection.size() != 1) return; IAdaptable element= (IAdaptable) selection.getFirstElement(); IResource resource= (IResource)element.getAdapter(IResource.class); if ((resource instanceof IContainer)) { // Create a menu flyout. MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$ submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource)); menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; IAdaptable element= (IAdaptable)selection.getFirstElement(); Object resource= element.getAdapter(IResource.class); if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } /** * Returns the shell to use for opening dialogs. * Used in this class, and in the actions. */ private Shell getShell() { return fViewer.getControl().getShell(); } protected final Display getDisplay() { return fViewer.getControl().getDisplay(); } /** * Returns the selection provider. */ private ISelectionProvider getSelectionProvider() { return fViewer; } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ abstract protected boolean isValidInput(Object element); /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element == null) return false; element= getSuitableJavaElement(element); if (element == null) return false; Object input= getViewer().getInput(); if (input == null) return false; if (input instanceof Collection) return ((Collection)input).contains(element); else return input.equals(element); } private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) { if (newInput == null) return part == fPreviousSelectionProvider; if (input instanceof IJavaElement && newInput instanceof IJavaElement) return getTypeComparator().compare(newInput, input) > 0; else return false; } protected boolean isAncestorOf(Object ancestor, Object element) { if (element instanceof IJavaElement && ancestor instanceof IJavaElement) return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element); return false; } private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) { if (element != null) return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent()); else return false; } public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!fProcessSelectionEvents || part == this || !(selection instanceof IStructuredSelection)) return; if (selection.isEmpty() && part instanceof JavaBrowsingPart && !(part instanceof ProjectsView)) return; // Set input Object newInput= getElementFromSingleSelection(selection); Object currentInput= (IJavaElement)getViewer().getInput(); if (newInput != null && newInput.equals(currentInput)) { IJavaElement elementToSelect= findElementToSelect(getElementFromSingleSelection(selection)); if (elementToSelect != null && getTypeComparator().compare(newInput, elementToSelect) < 0) setSelection(new StructuredSelection(elementToSelect), true); fPreviousSelectionProvider= part; return; } // Clear input if needed if (part != fPreviousSelectionProvider && newInput != null && !newInput.equals(currentInput) && isInputResetBy(newInput, currentInput, part)) { if (!isAncestorOf(newInput, currentInput)) setInput(null); fPreviousSelectionProvider= part; return; } else if (newInput == null && part == fPreviousSelectionProvider) { setInput(null); fPreviousSelectionProvider= part; return; } fPreviousSelectionProvider= part; // Set selection if (newInput instanceof IJavaElement) adjustInputAndSetSelection((IJavaElement)newInput); else setSelection(StructuredSelection.EMPTY, true); } protected void setInput(Object input) { if (input == null) setTitleImage(fOriginalTitleImage); else if (input instanceof Collection) { if (((Collection)input).isEmpty()) setTitleImage(fOriginalTitleImage); else { Object firstElement= ((Collection)input).iterator().next(); setTitleImage(fTitleProvider.getImage(firstElement)); } } else setTitleImage(fTitleProvider.getImage(input)); setViewerInput(input); } private void setViewerInput(Object input) { fProcessSelectionEvents= false; fViewer.setInput(input); fProcessSelectionEvents= true; } /** * Sets or clears the title image of this part and * store the orignal image on the first call. */ protected void setTitleImage(Image titleImage) { if (fOriginalTitleImage == null) fOriginalTitleImage= getTitleImage(); if (titleImage == null) titleImage= fOriginalTitleImage; super.setTitleImage(titleImage); } protected final StructuredViewer getViewer() { return fViewer; } protected ILabelProvider createLabelProvider() { return new StandardJavaUILabelProvider( StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS, StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, StandardJavaUILabelProvider.getAdornmentProviders(true, null) ); } protected ILabelProvider createTitleProvider() { return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS); } protected final ILabelProvider getLabelProvider() { return fLabelProvider; } protected final ILabelProvider getTitleProvider() { return fTitleProvider; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { return new ProblemTableViewer(parent, SWT.MULTI); } protected int getLabelProviderFlags() { return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS; } /** * Adds filters the viewer of this part. */ protected void addFilters() { // default is to have no filters } /** * Creates the the content provider of this part. */ protected BaseJavaElementContentProvider createContentProvider() { return new JavaElementContentProvider(true, this); // } protected void setInitialInput() { // Use the selection, if any ISelection selection= getSite().getPage().getSelection(); Object input= getElementFromSingleSelection(selection); if (!(input instanceof IJavaElement)) { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement) && input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); } setInput(findInputForJavaElement((JavaElement)input)); } protected void setInitialSelection() { // Use the selection, if any Object input; ISelection selection= getSite().getPage().getSelection(); if (selection != null && !selection.isEmpty()) input= getElementFromSingleSelection(selection); else { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement) && input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); else return; } if (findElementToSelect((IJavaElement)input) != null) adjustInputAndSetSelection((IJavaElement)input); } final protected void setHelp() { JavaUIHelp.setHelp(fViewer, getHelpContextId()); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ abstract protected String getHelpContextId(); /** * Adds additional listeners to this view. */ protected void hookViewerListeners() { fViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!fProcessSelectionEvents) return; if (JavaBrowsingPreferencePage.openEditorOnSingleClick()) new ShowInEditorAction().run(event.getSelection(), getSite().getPage()); else linkToEditor((IStructuredSelection)event.getSelection()); } }); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (fProcessSelectionEvents && !JavaBrowsingPreferencePage.openEditorOnSingleClick()) new ShowInEditorAction().run(event.getSelection(), getSite().getPage()); } }); } void adjustInputAndSetSelection(IJavaElement je) { je= getSuitableJavaElement(je); IJavaElement elementToSelect= findElementToSelect(je); IJavaElement newInput= findInputForJavaElement(je); if (elementToSelect == null && !isValidInput(newInput)) // Clear input setInput(null); else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) // Adjust input to selection setInput(findInputForJavaElement(je)); if (elementToSelect != null) setSelection(new StructuredSelection(elementToSelect), true); else setSelection(StructuredSelection.EMPTY, true); } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null) return null; if (isValidInput(je)) return je; return findInputForJavaElement(je.getParent()); } final protected IJavaElement findElementToSelect(Object obj) { if (obj instanceof IJavaElement) return findElementToSelect((IJavaElement)obj); return null; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ abstract protected IJavaElement findElementToSelect(IJavaElement je); private Object getElementFromSingleSelection(ISelection selection) { if (selection instanceof StructuredSelection && ((StructuredSelection)selection).size() == 1) return ((StructuredSelection)selection).getFirstElement(); return null; } /** * Gets the typeComparator. * @return Returns a JavaElementTypeComparator */ protected Comparator getTypeComparator() { return fTypeComparator; } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { if (selection == null || selection.isEmpty()) return; Object obj= selection.getFirstElement(); Object element= null; if (selection.size() == 1) { if (obj instanceof IJavaElement) { IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT); if (cu != null) element= getResourceFor(cu); if (element == null) element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE); } else if (obj instanceof IFile) element= obj; if (element == null) return; IWorkbenchPage page= getSite().getPage(); IEditorPart editorArray[]= page.getEditors(); for (int i= 0; i < editorArray.length; ++i) { IEditorPart editor= editorArray[i]; Object input= getElementOfInput(editor.getEditorInput()); if (input != null && input.equals(element)) { page.bringToTop(editor); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(editor, (IJavaElement) obj); return; } } } } private void setSelectionFromEditor(IWorkbenchPart part) { if (part == null) return; IWorkbenchPartSite site= part.getSite(); if (site == null) return; ISelectionProvider provider= site.getSelectionProvider(); if (provider != null) setSelectionFromEditor(part, provider.getSelection()); } private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) { if (part instanceof IEditorPart && JavaBrowsingPreferencePage.linkViewSelectionToEditor()) { IEditorInput ei= ((IEditorPart)part).getEditorInput(); if (selection instanceof ITextSelection) { int offset= ((ITextSelection)selection).getOffset(); IJavaElement element= getElementForInputAt(ei, offset); if (element != null) { adjustInputAndSetSelection(element); return; } } if (ei instanceof IFileEditorInput) { IFile file= ((IFileEditorInput)ei).getFile(); IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class); if (je == null) { setSelection(null, false); return; } adjustInputAndSetSelection(je); } else if (ei instanceof IClassFileEditorInput) { IClassFile cf= ((IClassFileEditorInput)ei).getClassFile(); adjustInputAndSetSelection(cf); } return; } } /** * 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; } private IResource getResourceFor(Object element) { if (element instanceof IJavaElement) { if (element instanceof IWorkingCopy) { IWorkingCopy wc= (IWorkingCopy)element; IJavaElement original= wc.getOriginalElement(); if (original != null) element= original; } try { element= ((IJavaElement)element).getUnderlyingResource(); } catch (JavaModelException e) { return null; } } if (!(element instanceof IResource) || ((IResource)element).isPhantom()) { return null; } return (IResource)element; } private void setSelection(ISelection selection, boolean reveal) { if (selection != null && selection.equals(fViewer.getSelection())) return; fProcessSelectionEvents= false; fViewer.setSelection(selection, reveal); fProcessSelectionEvents= true; } /** * Tries to find the given element in a workingcopy. */ protected static IJavaElement getWorkingCopy(IJavaElement input) { try { if (input instanceof ICompilationUnit) return EditorUtility.getWorkingCopy((ICompilationUnit)input); else return EditorUtility.getWorkingCopy(input, true); } catch (JavaModelException ex) { } return null; } /** * Returns the original element from which the specified working copy * element was created from. This is a handle only method, the * returned element may or may not exist. * * @param workingCopy the element for which to get the original * @return the original Java element or <code>null</code> if this is not a working copy element */ protected static IJavaElement getOriginal(IJavaElement workingCopy) { ICompilationUnit cu= getCompilationUnit(workingCopy); if (cu != null) return ((IWorkingCopy)cu).getOriginal(workingCopy); return null; } /** * Returns the compilation unit for the given java element. * * @param element the java element whose compilation unit is searched for * @return the compilation unit of the given java element */ protected static ICompilationUnit getCompilationUnit(IJavaElement element) { if (element == null) return null; if (element instanceof IMember) return ((IMember) element).getCompilationUnit(); int type= element.getElementType(); if (IJavaElement.COMPILATION_UNIT == type) return (ICompilationUnit) element; if (IJavaElement.CLASS_FILE == type) return null; return getCompilationUnit(element.getParent()); } /** * Converts the given Java element to one which is suitable for this * view. It takes into account wether the view shows working copies or not. * * @param element the Java element to be converted * @return an element suitable for this view */ protected IJavaElement getSuitableJavaElement(Object obj) { if (!(obj instanceof IJavaElement)) return null; IJavaElement element= (IJavaElement)obj; if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0) return element; if (element.getElementType() == IJavaElement.CLASS_FILE) return element; if (((BaseJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy()) { IJavaElement wc= getWorkingCopy(element); if (wc != null) element= wc; return element; } else { ICompilationUnit cu= getCompilationUnit(element); if (cu != null && ((IWorkingCopy)cu).isWorkingCopy()) return ((IWorkingCopy)cu).getOriginal(element); else return element; } } /** * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementForInputAt(IEditorInput input, int offset) { if (input instanceof IClassFileEditorInput) { try { return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset); } catch (JavaModelException ex) { return null; } } IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(input); if (unit != null) synchronized (unit) { try { unit.reconcile(null); return unit.getElementAt(offset); } catch (JavaModelException x) { } } return null; } protected IType getTypeForCU(ICompilationUnit cu) { cu= (ICompilationUnit)getSuitableJavaElement(cu); // Use primary type if possible IType primaryType= JavaModelUtil.findPrimaryType(cu); if (primaryType != null) return primaryType; // Use first top-level type try { IType[] types= cu.getTypes(); if (types.length > 0) return types[0]; else return null; } catch (JavaModelException ex) { return null; } } }
11,770
Bug 11770 java browsing: multi-selection disabled in 2 of 4 views
multi selection is disabled in the package and type views but it's enabled in project and member views
verified fixed
3839f03
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T15:41:17Z
2002-03-20T10:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/TypesView.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import org.eclipse.jface.viewers.ILabelProvider; 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.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider; public class TypesView extends JavaBrowsingPart { /** * Creates and returns the label provider for this part. * * @return the label provider * @see ILabelProvider */ protected ILabelProvider createLabelProvider() { return new StandardJavaUILabelProvider( StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS, StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS, StandardJavaUILabelProvider.getAdornmentProviders(true, null) ); } /** * Adds filters the viewer of this part. */ protected void addFilters() { getViewer().addFilter(new NonJavaElementFilter()); } /** * 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) { return element instanceof IPackageFragment; //|| element instanceof ICompilationUnit || element instanceof IClassFile; } /** * 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 ICompilationUnit) return super.isValidElement(((ICompilationUnit)element).getParent()); else if (element instanceof IType) { IType type= (IType)element; return type.getDeclaringType() == null && isValidElement(type.getCompilationUnit()); } 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.TYPE: IType type= ((IType)je).getDeclaringType(); if (type == null) type= (IType)je; return getSuitableJavaElement(type); case IJavaElement.COMPILATION_UNIT: return getTypeForCU((ICompilationUnit)je); case IJavaElement.CLASS_FILE: try { return findElementToSelect(((IClassFile)je).getType()); } catch (JavaModelException ex) { return null; } case IJavaElement.IMPORT_CONTAINER: case IJavaElement.IMPORT_DECLARATION: case IJavaElement.PACKAGE_DECLARATION: return findElementToSelect(je.getParent()); default: if (je instanceof IMember) return findElementToSelect(((IMember)je).getDeclaringType()); return null; } } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ protected String getHelpContextId() { return IJavaHelpContextIds.TYPES_VIEW; } }
11,842
Bug 11842 new TestCase not always initialized correctly
It works for CUs but not for classes Test Case: select class Test in the Packages view and create an new TestCase ==> only superclass field is initialized
resolved fixed
e03f80e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T16:26:40Z
2002-03-20T13:13:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.awt.Stroke; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ protected final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$ protected final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$ protected final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); updateStatus(findMostSevereStatus()); // put default class to test if (element != null) { IType enclosingType= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { enclosingType= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) enclosingType= JavaModelUtil.findPrimaryType(cu); } if (enclosingType != null) { try { if (!TestSearchEngine.isTestImplementor(enclosingType)) { fDefaultClassToTest= enclosingType.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return NewTestCaseCreationWizardPage.getMostSevere(new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } updateStatus(findMostSevereStatus()); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); restoreWidgetValues(); setFocus(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. * @param canBeModified Selects if the super class can be changed by the user */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type) throws JavaModelException { String constr= "public "+getTypeName()+"(String name) {super(name);}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(constr, null, false, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp; IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { setUp="/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown; IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start) || param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } if (newMethodsNames.contains(methodName.toString())) methodName.append("1"); //$NON-NLS-1$ newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } protected static GridData gridDataForDefaultForTypeName(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } public static Control createEmptySpace(Composite parent, int span) { Label label= new Label(parent, SWT.LEFT); GridData gd= new GridData(); gd.horizontalAlignment= gd.BEGINNING; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= span; gd.horizontalIndent= 0; gd.widthHint= 0; gd.heightHint= 0; label.setLayoutData(gd); return label; } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists fFirstTime= false; } } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see WizardPage#getNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); if (!val.isOK()) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ return status; } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.interface_not_visible",classToTestName));//$NON-NLS-1$ return status; } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Finds the most severe status from a array of stati. * An error is more severe than a warning, and a warning is more severe * than ok. */ public static IStatus getMostSevere(IStatus[] status) { IStatus max= null; for (int i= 0; i < status.length; i++) { IStatus curr= status[i]; if (curr.matches(IStatus.ERROR)) { return curr; } if (max == null || curr.getSeverity() > max.getSeverity()) { max= curr; } } return max; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); } /** * Use the dialog store to restore widget values to the values that they held * last time this wizard was used to completion */ private void restoreWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN); fMethodStubsButtons.setSelection(0, generateMain); fMethodStubsButtons.setEnabled(1, generateMain); fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER)); try { fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE)); } catch(NumberFormatException e) {} } } /** * Since Finish was pressed, write widget values to the dialog store so that they * will persist into the next invocation of this wizard page */ void saveWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0)); settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1)); settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection()); } } }
12,002
Bug 12002 TestCase wizard: error when pressing finish with an empty test name
the finish button should be disabled when the test name field is empty
resolved fixed
7f6ca90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T17:01:26Z
2002-03-21T05:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.awt.Stroke; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; 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.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ protected final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$ protected final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$ protected final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); updateStatus(findMostSevereStatus()); // put default class to test if (element != null) { IType classToTest= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { classToTest= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) classToTest= JavaModelUtil.findPrimaryType(cu); else { if (element instanceof IClassFile) { try { IClassFile cf= (IClassFile) element; if (cf.isStructureKnown()) classToTest= cf.getType(); } catch(JavaModelException e) { JUnitPlugin.log(e); } } } } if (classToTest != null) { try { if (!TestSearchEngine.isTestImplementor(classToTest)) { fDefaultClassToTest= classToTest.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return NewTestCaseCreationWizardPage.getMostSevere(new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } updateStatus(findMostSevereStatus()); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); restoreWidgetValues(); setFocus(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. * @param canBeModified Selects if the super class can be changed by the user */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type) throws JavaModelException { String constr= "public "+getTypeName()+"(String name) {super(name);}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(constr, null, false, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp; IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { setUp="/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown; IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start) || param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } if (newMethodsNames.contains(methodName.toString())) methodName.append("1"); //$NON-NLS-1$ newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } protected static GridData gridDataForDefaultForTypeName(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } public static Control createEmptySpace(Composite parent, int span) { Label label= new Label(parent, SWT.LEFT); GridData gd= new GridData(); gd.horizontalAlignment= gd.BEGINNING; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= span; gd.horizontalIndent= 0; gd.widthHint= 0; gd.heightHint= 0; label.setLayoutData(gd); return label; } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists fFirstTime= false; } } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see WizardPage#getNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); if (!val.isOK()) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ // return status; } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.interface_not_visible",classToTestName));//$NON-NLS-1$ // return status; } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Finds the most severe status from a array of stati. * An error is more severe than a warning, and a warning is more severe * than ok. */ public static IStatus getMostSevere(IStatus[] status) { IStatus max= null; for (int i= 0; i < status.length; i++) { IStatus curr= status[i]; if (curr.matches(IStatus.ERROR)) { return curr; } if (max == null || curr.getSeverity() > max.getSeverity()) { max= curr; } } return max; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); } /** * Use the dialog store to restore widget values to the values that they held * last time this wizard was used to completion */ private void restoreWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN); fMethodStubsButtons.setSelection(0, generateMain); fMethodStubsButtons.setEnabled(1, generateMain); fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER)); try { fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE)); } catch(NumberFormatException e) {} } } /** * Since Finish was pressed, write widget values to the dialog store so that they * will persist into the next invocation of this wizard page */ void saveWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0)); settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1)); settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection()); } } }
12,210
Bug 12210 rename temp: does not work on empty selection
null
resolved fixed
1158c15
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T17:05:43Z
2002-03-25T15:26:40Z
org.eclipse.jdt.ui/core
12,210
Bug 12210 rename temp: does not work on empty selection
null
resolved fixed
1158c15
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-25T17:05:43Z
2002-03-25T15:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/TempDeclarationFinder.java
12,195
Bug 12195 TestCase creation wizard: no progress when pressing super button
There is no progress shown in the wizard when pressing the browse button for selecting the super class. This is not consistent with the New Class wizard.
resolved fixed
1fdab7d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T08:11:30Z
2002-03-24T22:46:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/JUnitWizard.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.*; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; /** * The wizard base class for JUnit creation wizards. */ public class JUnitWizard extends BasicNewResourceWizard { /* * @see IWizard#performFinish() */ public boolean performFinish() { return false; } /** * Run a runnable */ protected boolean finishPage(IRunnableWithProgress runnable) { IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable); try { getContainer().run(false, true, op); } catch (InvocationTargetException e) { Shell shell= getShell(); String title= Messages.getString("NewJUnitWizard.op_error.title"); //$NON-NLS-1$ String message= Messages.getString("NewJUnitWizard.op_error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, shell, title, message); return false; } catch (InterruptedException e) { return false; } return true; } protected void openResource(final IResource resource) { if (resource.getType() == IResource.FILE) { final IWorkbenchPage activePage= JUnitPlugin.getDefault().getActivePage(); if (activePage != null) { final Display display= getShell().getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { try { activePage.openEditor((IFile)resource); } catch (PartInitException e) { JUnitPlugin.log(e); } } }); } } } } }
12,195
Bug 12195 TestCase creation wizard: no progress when pressing super button
There is no progress shown in the wizard when pressing the browse button for selecting the super class. This is not consistent with the New Class wizard.
resolved fixed
1fdab7d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T08:11:30Z
2002-03-24T22:46:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.awt.Stroke; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; 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.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ protected final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$ protected final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$ protected final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); updateStatus(findMostSevereStatus()); // put default class to test if (element != null) { IType classToTest= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { classToTest= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) classToTest= JavaModelUtil.findPrimaryType(cu); else { if (element instanceof IClassFile) { try { IClassFile cf= (IClassFile) element; if (cf.isStructureKnown()) classToTest= cf.getType(); } catch(JavaModelException e) { JUnitPlugin.log(e); } } } } if (classToTest != null) { try { if (!TestSearchEngine.isTestImplementor(classToTest)) { fDefaultClassToTest= classToTest.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return NewTestCaseCreationWizardPage.getMostSevere(new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } updateStatus(findMostSevereStatus()); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); restoreWidgetValues(); setFocus(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. * @param canBeModified Selects if the super class can be changed by the user */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type) throws JavaModelException { String constr= "public "+getTypeName()+"(String name) {super(name);}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(constr, null, false, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp; IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { setUp="/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown; IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start) || param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } if (newMethodsNames.contains(methodName.toString())) methodName.append("1"); //$NON-NLS-1$ newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } protected static GridData gridDataForDefaultForTypeName(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } public static Control createEmptySpace(Composite parent, int span) { Label label= new Label(parent, SWT.LEFT); GridData gd= new GridData(); gd.horizontalAlignment= gd.BEGINNING; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= span; gd.horizontalIndent= 0; gd.widthHint= 0; gd.heightHint= 0; label.setLayoutData(gd); return label; } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists if (getClassToTestText().equals("")) setPageComplete(false); fFirstTime= false; } } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see WizardPage#getNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); if (!val.isOK()) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ // return status; } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.interface_not_visible",classToTestName));//$NON-NLS-1$ // return status; } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Finds the most severe status from a array of stati. * An error is more severe than a warning, and a warning is more severe * than ok. */ public static IStatus getMostSevere(IStatus[] status) { IStatus max= null; for (int i= 0; i < status.length; i++) { IStatus curr= status[i]; if (curr.matches(IStatus.ERROR)) { return curr; } if (max == null || curr.getSeverity() > max.getSeverity()) { max= curr; } } return max; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); } /** * Use the dialog store to restore widget values to the values that they held * last time this wizard was used to completion */ private void restoreWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN); fMethodStubsButtons.setSelection(0, generateMain); fMethodStubsButtons.setEnabled(1, generateMain); fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER)); try { fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE)); } catch(NumberFormatException e) {} } } /** * Since Finish was pressed, write widget values to the dialog store so that they * will persist into the next invocation of this wizard page */ void saveWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0)); settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1)); settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection()); } } }
10,168
Bug 10168 NPE in externalize strings dialog
1. Select Java file 2. Externalize Strings 3. Next 4. Click "Browse" next to "test.properties". Click OK in the dialog without selecting anything. NPE occurs.
resolved fixed
5c14b4b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T11:41:15Z
2002-02-25T15:13:20Z
org.eclipse.jdt.ui/ui
10,168
Bug 10168 NPE in externalize strings dialog
1. Select Java file 2. Externalize Strings 3. Next 4. Click "Browse" next to "test.properties". Click OK in the dialog without selecting anything. NPE occurs.
resolved fixed
5c14b4b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T11:41:15Z
2002-02-25T15:13:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizardPage2.java
6,125
Bug 6125 JAR packager reports open files very late
1. edit in a file, don't save 2. open the JAR packager on it's project 3. enter all path, destination, name of jar packager description, etc 4. press finish: 'JAR creation failed: Unsaved Editors' 5. To save, I have to quit the wizard, save, open the wizard again and then enter all fields again - I should be allowed to create a JAR with unsaved editors - If not, there should be a dialog to allow saving
resolved fixed
715af9d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T15:17:40Z
2001-11-20T18:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.jarpackager; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Manifest; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.operation.ModalContext; import org.eclipse.jface.util.Assert; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.xml.sax.SAXException; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaStatusConstants; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; /** * Operation for exporting a resource and its children to a new JAR file. */ public class JarFileExportOperation implements IRunnableWithProgress { private JarWriter fJarWriter; private JarPackage fJarPackage; private IFile[] fDescriptionFiles; private Shell fParentShell; private Map fJavaNameToClassFilesMap; private IContainer fClassFilesMapContainer; private MultiStatus fProblems; /** * Creates an instance of this class. * * @param jarPackage the JAR package specification * @param parent the parent for the dialog, * or <code>null</code> if no dialog should be presented */ public JarFileExportOperation(JarPackage jarPackage, Shell parent) { this(parent); fJarPackage= jarPackage; } /** * Creates an instance of this class. * * @param descriptions an array with JAR package descriptions * @param parent the parent for the dialog, * or <code>null</code> if no dialog should be presented */ public JarFileExportOperation(IFile[] descriptions, Shell parent) { this(parent); fDescriptionFiles= descriptions; } /** * Adds a new warning to the list with the passed information. * Normally the export operation continues after a warning. * @param message the message * @param exception the throwable that caused the warning, or <code>null</code> */ private JarFileExportOperation(Shell parent) { fParentShell= parent; fProblems= new MultiStatus(JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"), null); //$NON-NLS-1$ } protected void addWarning(String message, Throwable error) { if (fJarPackage == null || fJarPackage.logWarnings()) fProblems.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error)); } /** * Adds a new error to the list with the passed information. * Normally an error terminates the export operation. * @param message the message * @param exception the throwable that caused the error, or <code>null</code> */ protected void addError(String message, Throwable error) { if (fJarPackage == null || fJarPackage.logErrors()) fProblems.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error)); } /** * Answers the number of file resources specified by the JAR package. * * @return int */ protected int countSelectedElements() { int count= 0; Iterator iter= fJarPackage.getSelectedElements().iterator(); while (iter.hasNext()) { Object element= iter.next(); IResource resource= null; if (element instanceof IJavaElement) { IJavaElement je= (IJavaElement)element; try { resource= je.getUnderlyingResource(); } catch (JavaModelException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$ return count; } } else resource= (IResource)element; if (resource.getType() == IResource.FILE) count++; else count += getTotalChildCount((IContainer)resource); } return count; } private int getTotalChildCount(IContainer container) { IResource[] members; try { members= container.members(); } catch (CoreException ex) { return 0; } int count= 0; for (int i= 0; i < members.length; i++) { if (members[i].getType() == IResource.FILE) count++; else count += getTotalChildCount((IContainer)members[i]); } return count; } /** * Exports the passed resource to the JAR file * * @param element the resource or JavaElement to export */ protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException { int leadSegmentsToRemove= 1; IPackageFragmentRoot pkgRoot= null; boolean isInJavaProject= false; IResource resource= null; IJavaProject jProject= null; if (element instanceof IJavaElement) { isInJavaProject= true; IJavaElement je= (IJavaElement)element; try { resource= je.getUnderlyingResource(); } catch (JavaModelException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$ return; } jProject= je.getJavaProject(); pkgRoot= JavaModelUtil.getPackageFragmentRoot(je); } else resource= (IResource)element; if (!resource.isAccessible()) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$ return; } if (resource.getType() == IResource.FILE) { if (!resource.isLocal(IResource.DEPTH_ZERO)) try { resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor); } catch (CoreException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$ return; } if (!isInJavaProject) { // check if it's a Java resource try { isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID); } catch (CoreException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$ return; } if (isInJavaProject) { jProject= JavaCore.create(resource.getProject()); try { IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1)); if (pkgFragment != null) pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment); else pkgRoot= jProject.findPackageFragmentRoot(resource.getFullPath().removeLastSegments(1)); } catch (JavaModelException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$ return; } } } if (pkgRoot != null) { leadSegmentsToRemove= pkgRoot.getPath().segmentCount(); if (fJarPackage.useSourceFolderHierarchy()&& !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH)) leadSegmentsToRemove--; } IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove); boolean isInOutputFolder= false; if (isInJavaProject) { try { isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath()); } catch (JavaModelException ex) { isInOutputFolder= false; } } exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath); exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder); progressMonitor.worked(1); ModalContext.checkCanceled(progressMonitor); } else if (element instanceof IPackageFragment) exportPackageFragment(progressMonitor, (IPackageFragment)element); else exportContainer(progressMonitor, resource); } private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException { Object[] children; try { children= pkgFragment.getChildren(); for (int i= 0; i < children.length; i++) exportElement(children[i], progressMonitor); children= pkgFragment.getNonJavaResources(); for (int i= 0; i < children.length; i++) exportElement(children[i], progressMonitor); } catch (CoreException e) { // this should never happen because an #isAccessible check is done before #members is invoked addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$ } } private void exportContainer(IProgressMonitor progressMonitor, IResource resource) throws java.lang.InterruptedException { IResource[] children= null; try { children= ((IContainer) resource).members(); } catch (CoreException e) { // this should never happen because an #isAccessible check is done before #members is invoked addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", resource.getFullPath()), e); //$NON-NLS-1$ } for (int i= 0; i < children.length; i++) exportElement(children[i], progressMonitor); } private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) { boolean isNonJavaResource= !isInJavaProject || pkgRoot == null; boolean isInClassFolder= false; try { isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY; } catch (JavaModelException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$ } if ((fJarPackage.areClassFilesExported() && ((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource))) || isInClassFolder && isClassFile(resource))) || (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) { try { progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$ fJarWriter.write((IFile) resource, destinationPath); } catch (IOException ex) { String message= ex.getMessage(); if (message == null) message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$ addWarning(message , ex); } catch (CoreException ex) { String message= ex.getMessage(); if (message == null) message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$ addWarning(message, ex); } } } private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) { if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) { try { // find corresponding file(s) on classpath and export Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor); IPath baseDestinationPath= destinationPath.removeLastSegments(1); while (iter.hasNext()) { IFile file= (IFile)iter.next(); if (!resource.isLocal(IResource.DEPTH_ZERO)) file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor); IPath classFilePath= baseDestinationPath.append(file.getName()); progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$ fJarWriter.write(file, classFilePath); } } catch (IOException ex) { String message= ex.getMessage(); if (message == null) message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$ addWarning(message , ex); } catch (CoreException ex) { String message= ex.getMessage(); if (message == null) message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$ addWarning(message, ex); } } } /** * Exports the resources as specified by the JAR package. */ protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException { Iterator iter= fJarPackage.getSelectedElements().iterator(); while (iter.hasNext()) exportElement(iter.next(), progressMonitor); } /** * Returns an iterator on a list with files that correspond to the * passed file and that are on the classpath of its project. * * @param file the file for which to find the corresponding classpath resources * @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed) * @param javaProject the javaProject that contains the file * @return the iterator over the corresponding classpath files for the given file */ protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException { IPath outputPath= javaProject.getOutputLocation(); IContainer outputContainer; if (javaProject.getProject().getFullPath().equals(outputPath)) outputContainer= javaProject.getProject(); else { outputContainer= createFolderHandle(outputPath); if (outputContainer == null || !outputContainer.isAccessible()) { String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$ throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null)); } } if (isJavaFile(file)) { // Java CU - search files with .class ending boolean hasErrors= fJarPackage.hasCompileErrors(file); boolean hasWarnings= fJarPackage.hasCompileWarnings(file); boolean canBeExported= canBeExported(hasErrors, hasWarnings); if (!canBeExported) return Collections.EMPTY_LIST.iterator(); reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported); IContainer classContainer= outputContainer; if (pathInJar.segmentCount() > 1) classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1)); if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) { fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer); fClassFilesMapContainer= classContainer; } ArrayList classFiles= (ArrayList)fJavaNameToClassFilesMap.get(file.getName()); if (classFiles == null || classFiles.isEmpty()) { String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$ throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null)); } return classFiles.iterator(); } else { // resource - search file with same name List binaryFiles= new ArrayList(1); IFile cpFile= outputContainer.getFile(pathInJar); if (cpFile.isAccessible()) { if (!cpFile.isLocal(IResource.DEPTH_ZERO)) cpFile.setLocal(true , IResource.DEPTH_ZERO, progressMonitor); binaryFiles.add(cpFile); } else { String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceOnCasspathNotAccessible", cpFile.getFullPath()); //$NON-NLS-1$ throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null)); } return binaryFiles.iterator(); } } /** * Answers whether the given resource is a Java file. * The resource must be a file whose file name ends with ".java". * * @return a <code>true<code> if the given resource is a Java file */ boolean isJavaFile(IResource file) { return file != null && file.getType() == IFile.FILE && file.getFileExtension() != null && file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$ } /** * Answers whether the given resource is a class file. * The resource must be a file whose file name ends with ".class". * * @return a <code>true<code> if the given resource is a class file */ boolean isClassFile(IResource file) { return file != null && file.getType() == IFile.FILE && file.getFileExtension() != null && file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$ } /* * Builds and returns a map that has the class files * for each java file in a given directory */ private Map buildJavaToClassMap(IContainer container) throws CoreException { if (container == null || !container.isAccessible()) return new HashMap(0); /* * XXX: Bug 6584: Need a way to get class files for a java file (or CU) */ org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader; IResource[] members= container.members(); Map map= new HashMap(members.length); for (int i= 0; i < members.length; i++) { if (isClassFile(members[i])) { IFile classFile= (IFile)members[i]; try { cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile()); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$ continue; } catch (IOException ex) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$ continue; } if (cfReader != null) { if (cfReader.sourceFileName() == null) { addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$ continue; } String javaName= new String(cfReader.sourceFileName()); Object classFiles= map.get(javaName); if (classFiles == null) { classFiles= new ArrayList(3); map.put(javaName, classFiles); } ((ArrayList)classFiles).add(classFile); } } } return map; } /** * Creates a file resource handle for the file with the given workspace path. * This method does not create the file resource; this is the responsibility * of <code>createFile</code>. * * @param filePath the path of the file resource to create a handle for * @return the new file resource handle * @see #createFile */ protected IFile createFileHandle(IPath filePath) { if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2) return JavaPlugin.getWorkspace().getRoot().getFile(filePath); else return null; } /** * Creates a folder resource handle for the folder with the given workspace path. * * @param folderPath the path of the folder to create a handle for * @return the new folder resource handle */ protected IFolder createFolderHandle(IPath folderPath) { if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2) return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath); else return null; } /** * Returns the status of this operation. * If there were any errors, the result is a status object containing * individual status objects for each error. * If there were no errors, the result is a status object with error code <code>OK</code>. * * @return the status of this operation */ public IStatus getStatus() { if (fProblems.getSeverity() == IStatus.ERROR) { String message= null; if (fDescriptionFiles != null && fDescriptionFiles.length > 1) message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$ else message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$ // Create new status because we want another message - no API to set message return new MultiStatus(JavaPlugin.getPluginId(), 0, fProblems.getChildren(), message, null); } return fProblems; } /** * Answer a boolean indicating whether the passed child is a descendant * of one or more members of the passed resources collection * * @param resources a List contain potential parents * @param child the resource to test * @return a <code>boolean</code> indicating if the child is a descendant */ protected boolean isDescendant(List resources, IResource child) { if (child.getType() == IResource.PROJECT) return false; IResource parent= child.getParent(); if (resources.contains(parent)) return true; return isDescendant(resources, parent); } protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException { return (!hasErrors && !hasWarnings) || (hasErrors && fJarPackage.exportErrors()) || (hasWarnings && fJarPackage.exportWarnings()); } protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) { if (hasErrors) { if (canBeExported) addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$ else addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$ } if (hasWarnings) { if (canBeExported) addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$ else addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$ } } /** * Exports the resources as specified by the JAR package. * * @param progressMonitor the progress monitor that displays the progress * @see #getStatus() */ public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException { if (fJarPackage != null) singleRun(progressMonitor); else { int jarCount= fDescriptionFiles.length; progressMonitor.beginTask("", jarCount); //$NON-NLS-1$ try { for (int i= 0; i < jarCount; i++) { SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1); fJarPackage= readJarPackage(fDescriptionFiles[i]); if (fJarPackage != null) singleRun(subProgressMonitor); } } finally { progressMonitor.done(); } } } public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException { try { if (!preconditionsOK()) throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$ int totalWork= countSelectedElements(); if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded()) { int subMonitorTicks= totalWork/10; totalWork += subMonitorTicks; progressMonitor.beginTask("", totalWork); //$NON-NLS-1$ SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); buildProjects(subProgressMonitor); } else progressMonitor.beginTask("", totalWork); //$NON-NLS-1$ fJarWriter= new JarWriter(fJarPackage, fParentShell); exportSelectedElements(progressMonitor); if (getStatus().getSeverity() != IStatus.ERROR) { progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$ saveFiles(); } } catch (IOException ex) { String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFle", ex.getMessage()); //$NON-NLS-1$ addError(message, ex); throw new InvocationTargetException(ex, message); } catch (CoreException ex) { String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFileDueToInvalidManifest", ex.getMessage()); //$NON-NLS-1$ addError(message, ex); throw new InvocationTargetException(ex, message); } finally { try { if (fJarWriter != null) fJarWriter.close(); } catch (IOException ex) { String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCloseJarFile", ex.getMessage()); //$NON-NLS-1$ addError(message, ex); throw new InvocationTargetException(ex, message); } progressMonitor.done(); } } protected boolean preconditionsOK() { if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) { addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$ return false; } if (fJarPackage.getSelectedElements() == null || fJarPackage.getSelectedElements().size() == 0) { addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$ return false; } if (fJarPackage.getJarLocation() == null) { addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$ return false; } if (!fJarPackage.doesManifestExist()) { addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$ return false; } if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) { addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$ return false; } IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors(); if (dirtyEditors.length > 0) { List unsavedFiles= new ArrayList(dirtyEditors.length); List selection= fJarPackage.getSelectedResources(); for (int i= 0; i < dirtyEditors.length; i++) { if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) { IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile(); if (selection.contains(dirtyFile)) { unsavedFiles.add(dirtyFile); addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFile.getFullPath()), null); //$NON-NLS-1$ } } } if (!unsavedFiles.isEmpty()) return false; } return true; } protected void saveFiles() { // Save the manifest if (fJarPackage.isManifestSaved()) { try { saveManifest(); } catch (CoreException ex) { addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$ } catch (IOException ex) { addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$ } } // Save the description if (fJarPackage.isDescriptionSaved()) { try { saveDescription(); } catch (CoreException ex) { addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$ } catch (IOException ex) { addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$ } } } protected void saveDescription() throws CoreException, IOException { // Adjust JAR package attributes if (fJarPackage.isManifestReused()) fJarPackage.setGenerateManifest(false); ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream(); JarPackageWriter objectStream= new JarPackageWriter(objectStreamOutput); ByteArrayInputStream fileInput= null; try { objectStream.writeXML(fJarPackage); fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray()); if (fJarPackage.getDescriptionFile().isAccessible()) { if (fJarPackage.canOverwriteDescription(fParentShell)) fJarPackage.getDescriptionFile().setContents(fileInput, true, true, null); } else { fJarPackage.getDescriptionFile().create(fileInput, true, null); } } finally { if (fileInput != null) fileInput.close(); if (objectStream != null) objectStream.close(); } } protected void saveManifest() throws CoreException, IOException { ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream(); ByteArrayInputStream fileInput= null; try { Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage); manifest.write(manifestOutput); fileInput= new ByteArrayInputStream(manifestOutput.toByteArray()); if (fJarPackage.getManifestFile().isAccessible()) { if (fJarPackage.canOverwriteManifest(fParentShell)) fJarPackage.getManifestFile().setContents(fileInput, true, true, null); } else { fJarPackage.getManifestFile().create(fileInput, true, null); } } finally { if (manifestOutput != null) manifestOutput.close(); if (fileInput != null) fileInput.close(); } } /** * Reads the JAR package spec from file. */ protected JarPackage readJarPackage(IFile description) { Assert.isLegal(description.isAccessible()); Assert.isNotNull(description.getFileExtension()); Assert.isLegal(description.getFileExtension().equals(JarPackage.DESCRIPTION_EXTENSION)); JarPackage jarPackage= null; JarPackageReader reader= null; try { reader= new JarPackageReader(description.getContents()); // Do not save - only generate JAR jarPackage= reader.readXML(); jarPackage.setSaveManifest(false); jarPackage.setSaveDescription(false); } catch (CoreException ex) { addError(JarPackagerMessages.getString("JarFileExportOperation.errorReadingJarPackageFromDescription"), ex); //$NON-NLS-1$ } catch (IOException ex) { String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorReadingFile", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$ addError(message, null); } catch (SAXException ex) { String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.badXmlFormat", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$ addError(message, null); } finally { if ((jarPackage == null || jarPackage.logWarnings()) && reader != null) // AddWarnings fProblems.addAll(reader.getWarnings()); try { if (reader != null) reader.close(); } catch (IOException ex) { addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorClosingJarPackageDescriptionReader", description.getFullPath()), ex); //$NON-NLS-1$ } } return jarPackage; } private boolean isAutoBuilding() { return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding(); } private void buildProjects(IProgressMonitor progressMonitor) { Set builtProjects= new HashSet(10); Iterator iter= fJarPackage.getSelectedElementsClosure(); while (iter.hasNext()) { IProject project= null; Object element= iter.next(); if (element instanceof IResource) project= ((IResource)element).getProject(); else if (element instanceof IJavaElement) project= ((IJavaElement)element).getJavaProject().getProject(); if (project != null && !builtProjects.contains(project)) { try { project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor); } catch (CoreException ex) { String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$ addError(message, ex); } finally { // don't try to build same project a second time even if it failed builtProjects.add(project); } } } } }
11,851
Bug 11851 generated new TestCase differes form generated new class
It would be nice if the generation of a new test case would do the same as generation of a new class. The thing which I noticed: new Class wizards adds javadoc while new Test Case wizard does not. /** * Constructor for AA. * @param name */ public AA(String name) { super(name); }
resolved fixed
8834612
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T16:06:08Z
2002-03-20T13:13:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.awt.Stroke; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; 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.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ protected final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$ protected final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$ protected final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; //$NON-NLS-1$ private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); doStatusUpdate(); // put default class to test if (element != null) { IType classToTest= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { classToTest= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) classToTest= JavaModelUtil.findPrimaryType(cu); else { if (element instanceof IClassFile) { try { IClassFile cf= (IClassFile) element; if (cf.isStructureKnown()) classToTest= cf.getType(); } catch(JavaModelException e) { JUnitPlugin.log(e); } } } } if (classToTest != null) { try { if (!TestSearchEngine.isTestImplementor(classToTest)) { fDefaultClassToTest= classToTest.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * @see NewContainerWizardPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } doStatusUpdate(); } // ------ validation -------- private void doStatusUpdate() { // status of all used components IStatus[] status= new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }; // the mode severe status will be displayed and the ok button enabled/disabled. updateStatus(status); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); restoreWidgetValues(); setFocus(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type) throws JavaModelException { String constr= "public "+getTypeName()+"(String name) {super(name);}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(constr, null, false, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp; IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { setUp="/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown; IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } if (methodTemplate != null) { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n" + //$NON-NLS-1$ "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start) || param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } if (newMethodsNames.contains(methodName.toString())) methodName.append("1"); //$NON-NLS-1$ newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists if (getClassToTestText().equals("")) //$NON-NLS-1$ setPageComplete(false); fFirstTime= false; } } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see IWizardPage#canFlipToNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); // if (!val.isOK()) { if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String[] {(type.isInterface())?Messages.getString("Interface"):Messages.getString("Class") , classToTestName})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); } /** * Use the dialog store to restore widget values to the values that they held * last time this wizard was used to completion */ private void restoreWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN); fMethodStubsButtons.setSelection(0, generateMain); fMethodStubsButtons.setEnabled(1, generateMain); fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER)); try { fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE)); } catch(NumberFormatException e) {} } } /** * Since Finish was pressed, write widget values to the dialog store so that they * will persist into the next invocation of this wizard page */ void saveWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0)); settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1)); settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection()); } } }
11,773
Bug 11773 java browsing: sorter for Members view
i'd like to be able to sort and filters things in package and type views (sorting more important)
resolved fixed
7d2c273
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T16:09:27Z
2002-03-20T10:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/LexicalSortingAction.java
11,773
Bug 11773 java browsing: sorter for Members view
i'd like to be able to sort and filters things in package and type views (sorting more important)
resolved fixed
7d2c273
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-26T16:09:27Z
2002-03-20T10:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/MembersView.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; 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.viewsupport.MemberFilterActionGroup; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider; public class MembersView extends JavaBrowsingPart { private MemberFilterActionGroup fMemberFilterActionGroup; /** * Creates and returns the label provider for this part. * * @return the label provider * @see ILabelProvider */ protected ILabelProvider createLabelProvider() { return new StandardJavaUILabelProvider( StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS, StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS, StandardJavaUILabelProvider.getAdornmentProviders(true, null) ); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ protected String getHelpContextId() { return IJavaHelpContextIds.MEMBERS_VIEW; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { ProblemTreeViewer viewer= new ProblemTreeViewer(parent, SWT.MULTI); fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaPlugin.ID_PACKAGES_VIEW); return viewer; } /** * Adds filters the viewer of this part. */ protected void addFilters() { } protected void fillToolBar(IToolBarManager tbm) { fMemberFilterActionGroup.contributeToToolBar(tbm); } /** * 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 IType) { IType type= (IType)element; return type.isBinary() || type.getDeclaringType() == null; } 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 IMember) return super.isValidElement(((IMember)element).getDeclaringType()); else if (element instanceof IImportContainer || element instanceof IImportDeclaration) { IJavaElement parent= ((IJavaElement)element).getParent(); if (parent.getElementType() == IJavaElement.CLASS_FILE) { IType type; try { type= ((IClassFile)parent).getType(); } catch (JavaModelException ex) { return false; } return isValidElement(type); } else if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { IType[] types; try { types= ((ICompilationUnit)parent).getAllTypes(); } catch (JavaModelException ex) { return false; } for (int i= 0; i < types.length; i++) { boolean result= isValidElement(types[i]); if (result) return true; } } } 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.METHOD: case IJavaElement.FIELD: case IJavaElement.TYPE: case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: case IJavaElement.IMPORT_DECLARATION: je= getSuitableJavaElement(je); if (je != null) return je; default: return null; } } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; switch (je.getElementType()) { case IJavaElement.TYPE: IType type= ((IType)je).getDeclaringType(); if (type == null) return je; else return findInputForJavaElement(type); case IJavaElement.COMPILATION_UNIT: return getTypeForCU((ICompilationUnit)je); case IJavaElement.CLASS_FILE: try { return findInputForJavaElement(((IClassFile)je).getType()); } catch (JavaModelException ex) { return null; } case IJavaElement.IMPORT_DECLARATION: return findInputForJavaElement(je.getParent()); case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: IJavaElement parent= je.getParent(); if (parent instanceof ICompilationUnit) { IType[] types; try { types= ((ICompilationUnit)parent).getAllTypes(); } catch (JavaModelException ex) { return null; } if (types.length > 0) return types[0]; else return null; } else if (parent instanceof IClassFile) return findInputForJavaElement(parent); default: if (je instanceof IMember) return findInputForJavaElement(((IMember)je).getDeclaringType()); } return null; } }
11,689
Bug 11689 NPE creating a test case in empty workbench
If you create a project and then a JUnit TestCase when there are no other classes in the image you will get a NullPointerException when you select the browse button on the Test Class entry. STEPS 1) Create a ConfigurableProject 2) Create a JUnit Test class. In the creation dialog select the 3rd browse button. Walkback: java.lang.NullPointerException at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.chooseClassToTestTyp e(NewTestCaseCreationWizardPage.java:318) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.classToTestButtonPre ssed(NewTestCaseCreationWizardPage.java:293) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.access$0 (NewTestCaseCreationWizardPage.java:292) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage$3.widgetSelected (NewTestCaseCreationWizardPage.java:279) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.actions.NewWizardAction.run(NewWizardAction.java:74) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:698) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
resolved fixed
4f1a191
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-27T10:34:12Z
2002-03-19T20:33:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestCaseCreationWizardPage.java
package org.eclipse.jdt.junit.wizards; import java.awt.Stroke; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; 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.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ protected final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$ protected final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$ protected final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; //$NON-NLS-1$ private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private SelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ Messages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ Messages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(Messages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fMethodStubsButtons.setSelectionGroupListener(new SelectionButtonGroup.SelectionButtonGroupListener() { public void groupChanged(SelectionButtonGroup field) { field.setEnabled(1, field.isSelected(0)); } }); fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); doStatusUpdate(); // put default class to test if (element != null) { IType classToTest= null; // evaluate the enclosing type IPackageFragment pack= (IPackageFragment) JavaModelUtil.findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT); IType typeInCompUnit= (IType) JavaModelUtil.findElementOfKind(element, IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { classToTest= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(element, IJavaElement.COMPILATION_UNIT); if (cu != null) classToTest= JavaModelUtil.findPrimaryType(cu); else { if (element instanceof IClassFile) { try { IClassFile cf= (IClassFile) element; if (cf.isStructureKnown()) classToTest= cf.getType(); } catch(JavaModelException e) { JUnitPlugin.log(e); } } } } if (classToTest != null) { try { if (!TestSearchEngine.isTestImplementor(classToTest)) { fDefaultClassToTest= classToTest.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * @see NewContainerWizardPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } } doStatusUpdate(); } // ------ validation -------- private void doStatusUpdate() { // status of all used components IStatus[] status= new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }; // the mode severe status will be displayed and the ok button enabled/disabled. updateStatus(status); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); restoreWidgetValues(); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(Messages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(Messages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(Messages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Gets the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } public IType getClassToTest() { return fClassToTest; } /** * Sets the class to test name. */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type, imports); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String constr= ""; //$NON-NLS-1$ IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod constrMethod= superTypes[i].getMethod(superTypes[i].getElementName(), new String[] {"Ljava.lang.String;"}); //$NON-NLS-1$ if (constrMethod.exists() && constrMethod.isConstructor()) { methodTemplate= constrMethod; break; } } } } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (methodTemplate != null) { GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; constr= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { StringBuffer field= new StringBuffer(); if (settings.createComments) field.append("/**\n * The name of the test case.\n */\n"); //$NON-NLS-1$ field.append("private String fName;\n\n"); //$NON-NLS-1$ type.createField(field.toString(), null, true, null); if (settings.createComments) constr="/**\n * Constructs a test case with the given name.\n */\n"; //$NON-NLS-1$ constr += "public "+getTypeName()+"(String name) {\nfName= name;\n}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(constr, null, true, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (fMethodStubsButtons.isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (fMethodStubsButtons.getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + getTypeName() + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n\n"); //$NON-NLS-1$ type.createMethod(main.toString(), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp= ""; //$NON-NLS-1$ IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (methodTemplate != null) { GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { if (settings.createComments) setUp= "/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n"; //$NON-NLS-1$ setUp+= "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, IImportsStructure imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown= ""; //$NON-NLS-1$ IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (methodTemplate != null) { GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { if (settings.createComments) tearDown="/**\n * Tears down the fixture, for example, close a network connection.\n * This method is called after a test is executed.\n * @throws Exception\n */\n"; //$NON-NLS-1$ tearDown+= "protected void "+TEARDOWN+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; newMethod.append("/*\n * Test for "+Signature.toString(method.getReturnType())+" "+method.getElementName()+"("); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start) || param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } /* Should I for examples have methods * void foo(java.lang.StringBuffer sb) {} * void foo(mypackage1.StringBuffer sb) {} * void foo(mypackage2.StringBuffer sb) {} * I will get in the test class: * testFooStringBuffer() * testFooStringBuffer1() * testFooStringBuffer2() */ if (newMethodsNames.contains(methodName.toString())) { int suffix= 1; while (newMethodsNames.contains(methodName.toString() + Integer.toString(suffix))) suffix++; methodName.append(Integer.toString(suffix)); } newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists if (getClassToTestText().equals("")) //$NON-NLS-1$ setPageComplete(false); fFirstTime= false; } if (visible) setFocus(); } public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getUnderlyingResource(); for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, Messages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(Messages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(Messages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(Messages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(Messages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see IWizardPage#canFlipToNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); // if (!val.isOK()) { if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(Messages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String[] {(type.isInterface())?Messages.getString("Interface"):Messages.getString("Class") , classToTestName})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } fClassToTest= type; } catch (JavaModelException e) { status.setError(Messages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, classToTestName); } return type; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); fTestClassText.setSelection(fTestClassText.getText().length(), fTestClassText.getText().length()); } /** * Use the dialog store to restore widget values to the values that they held * last time this wizard was used to completion */ private void restoreWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN); fMethodStubsButtons.setSelection(0, generateMain); fMethodStubsButtons.setEnabled(1, generateMain); fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER)); try { fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE)); } catch(NumberFormatException e) {} } } /** * Since Finish was pressed, write widget values to the dialog store so that they * will persist into the next invocation of this wizard page */ void saveWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0)); settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1)); settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection()); } } }
11,689
Bug 11689 NPE creating a test case in empty workbench
If you create a project and then a JUnit TestCase when there are no other classes in the image you will get a NullPointerException when you select the browse button on the Test Class entry. STEPS 1) Create a ConfigurableProject 2) Create a JUnit Test class. In the creation dialog select the 3rd browse button. Walkback: java.lang.NullPointerException at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.chooseClassToTestTyp e(NewTestCaseCreationWizardPage.java:318) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.classToTestButtonPre ssed(NewTestCaseCreationWizardPage.java:293) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.access$0 (NewTestCaseCreationWizardPage.java:292) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage$3.widgetSelected (NewTestCaseCreationWizardPage.java:279) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.actions.NewWizardAction.run(NewWizardAction.java:74) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:698) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
resolved fixed
4f1a191
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-27T10:34:12Z
2002-03-19T20:33:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestSuiteCreationWizard.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.IEditorPart; /** * A wizard for creating TestSuites. */ public class NewTestSuiteCreationWizard extends JUnitWizard { private NewTestSuiteCreationWizardPage fPage; public NewTestSuiteCreationWizard() { super(); //setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS); //setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle(Messages.getString("Wizard.title.new")); //$NON-NLS-1$ } /* * @see Wizard#createPages */ public void addPages() { super.addPages(); //IWorkspace workspace= JavaPlugin.getWorkspace(); IWorkspace workspace= ResourcesPlugin.getWorkspace(); fPage= new NewTestSuiteCreationWizardPage(); addPage(fPage); fPage.init(getSelection()); } /* * @see Wizard#performFinish */ public boolean performFinish() { IPackageFragment pack= fPage.getPackageFragment(); String filename= fPage.getTypeName() + ".java"; //$NON-NLS-1$ ICompilationUnit cu= pack.getCompilationUnit(filename); if (cu.exists()) { IEditorPart cu_ep= EditorUtility.isOpenInEditor(cu); if (cu_ep != null && cu_ep.isDirty()) { boolean saveUnsavedChanges= MessageDialog.openQuestion(fPage.getShell(), Messages.getString("NewTestSuiteWiz.unsavedchangesDialog.title"), Messages.getFormattedString("NewTestSuiteWiz.unsavedchangesDialog.message", filename)); //$NON-NLS-1$ //$NON-NLS-2$ if (saveUnsavedChanges) { ProgressMonitorDialog progressDialog= new ProgressMonitorDialog(fPage.getShell()); try { progressDialog.run(false, false, getRunnableSave(cu_ep)); } catch (Exception e) { JUnitPlugin.log(e); } } } IType suiteType= cu.getType(fPage.getTypeName()); IMethod suiteMethod= suiteType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (suiteMethod.exists()) { try { ISourceRange range= suiteMethod.getSourceRange(); IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); int start= originalContent.indexOf(NewTestSuiteCreationWizardPage.startMarker); if (start > -1) { int end= originalContent.indexOf(NewTestSuiteCreationWizardPage.endMarker, start); if (end < 0) { fPage.cannotUpdateSuiteError(); return false; } } else { fPage.cannotUpdateSuiteError(); return false; } } catch (JavaModelException e) { JUnitPlugin.log(e); return false; } } } if (finishPage(fPage.getRunnable())) { if (!fPage.hasUpdatedExistingClass()) postCreatingType(); return true; } return false; } protected void postCreatingType() { IType newClass= fPage.getCreatedType(); ICompilationUnit cu= newClass.getCompilationUnit(); if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); //added here } try { IResource resource= cu.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { JUnitPlugin.log(e); } } public NewTestSuiteCreationWizardPage getPage() { return fPage; } public IRunnableWithProgress getRunnableSave(final IEditorPart cu_ep) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } cu_ep.doSave(monitor); } }; } }
11,689
Bug 11689 NPE creating a test case in empty workbench
If you create a project and then a JUnit TestCase when there are no other classes in the image you will get a NullPointerException when you select the browse button on the Test Class entry. STEPS 1) Create a ConfigurableProject 2) Create a JUnit Test class. In the creation dialog select the 3rd browse button. Walkback: java.lang.NullPointerException at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.chooseClassToTestTyp e(NewTestCaseCreationWizardPage.java:318) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.classToTestButtonPre ssed(NewTestCaseCreationWizardPage.java:293) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.access$0 (NewTestCaseCreationWizardPage.java:292) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage$3.widgetSelected (NewTestCaseCreationWizardPage.java:279) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.actions.NewWizardAction.run(NewWizardAction.java:74) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:698) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
resolved fixed
4f1a191
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-27T10:34:12Z
2002-03-19T20:33:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/NewTestSuiteCreationWizardPage.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; /** * Wizard page to select the test classes to include * in the test suite. */ public class NewTestSuiteCreationWizardPage extends NewTypeWizardPage { private final static String PAGE_NAME= "NewTestSuiteCreationWizardPage"; //$NON-NLS-1$ private final static String CLASSES_IN_SUITE= PAGE_NAME + ".classesinsuite"; //$NON-NLS-1$ private final static String SUITE_NAME= PAGE_NAME + ".suitename"; //$NON-NLS-1$ private final static String SELECTED_CLASSES_LABEL_TEXT_ONE= " class selected."; //$NON-NLS-1$ private final static String SELECTED_CLASSES_LABEL_TEXT_MANY= " classes selected."; //$NON-NLS-1$ private IPackageFragment fCurrentPackage; private CheckboxTableViewer fClassesInSuiteTable; private Button fSelectAllButton; private Button fDeselectAllButton; private Label fSelectedClassesLabel; private Label fSuiteNameLabel; private Text fSuiteNameText; private String fSuiteNameTextInitialValue; private boolean fUpdatedExistingClassButton; public static final String startMarker= "//$JUnit-BEGIN$"; //$NON-NLS-1$ public static final String endMarker= "//$JUnit-END$"; //$NON-NLS-1$ protected IStatus fClassesInSuiteStatus; protected IStatus fSuiteNameStatus; public NewTestSuiteCreationWizardPage() { super(true, PAGE_NAME); fSuiteNameStatus= new JUnitStatus(); fSuiteNameTextInitialValue= ""; //$NON-NLS-1$ setTitle(Messages.getString("NewTestSuiteWizPage.title")); //$NON-NLS-1$ setDescription(Messages.getString("NewTestSuiteWizPage.description")); //$NON-NLS-1$ fClassesInSuiteStatus= new JUnitStatus(); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createSuiteNameControl(composite, nColumns); setTypeName("AllTests",true); //$NON-NLS-1$ createSeparator(composite, nColumns); createClassesInSuiteControl(composite, nColumns); setControl(composite); } /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); doStatusUpdate(); } /** * @see NewContainerWizardPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); updateClassesInSuiteTable(); } else if (fieldName.equals(CLASSES_IN_SUITE)) { fClassesInSuiteStatus= classesInSuiteChanged(); updateSelectedClassesLabel(); } else if (fieldName.equals(SUITE_NAME)) { fSuiteNameStatus= testSuiteChanged(); } doStatusUpdate(); } // ------ validation -------- private void doStatusUpdate() { // status of all used components IStatus[] status= new IStatus[] { fContainerStatus, fPackageStatus, fSuiteNameStatus, fClassesInSuiteStatus }; // the mode severe status will be displayed and the ok button enabled/disabled. updateStatus(status); } public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { setFocus(); updateClassesInSuiteTable(); } } protected void updateClassesInSuiteTable() { if (fClassesInSuiteTable != null) { IPackageFragment pack= getPackageFragment(); if (pack == null) { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) pack= root.getPackageFragment(""); //$NON-NLS-1$ else return; } fCurrentPackage= pack; fClassesInSuiteTable.setInput(pack); fClassesInSuiteTable.setAllChecked(true); updateSelectedClassesLabel(); } } protected void createClassesInSuiteControl(Composite parent, int nColumns) { if (fClassesInSuiteTable == null) { Label label = new Label(parent, SWT.LEFT); label.setText(Messages.getString("NewTestSuiteWizPage.classes_in_suite.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalAlignment = GridData.FILL; gd.horizontalSpan = nColumns; label.setLayoutData(gd); fClassesInSuiteTable= CheckboxTableViewer.newCheckList(parent, SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= 200; gd.horizontalSpan= nColumns-1; fClassesInSuiteTable.getTable().setLayoutData(gd); fClassesInSuiteTable.setContentProvider(new ClassesInSuitContentProvider()); fClassesInSuiteTable.setLabelProvider(new JavaElementLabelProvider()); fClassesInSuiteTable.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { handleFieldChanged(CLASSES_IN_SUITE); } }); Composite buttonContainer= new Composite(parent, SWT.NONE); gd= new GridData(GridData.FILL_VERTICAL); buttonContainer.setLayoutData(gd); GridLayout buttonLayout= new GridLayout(); buttonLayout.marginWidth= 0; buttonLayout.marginHeight= 0; buttonContainer.setLayout(buttonLayout); fSelectAllButton= new Button(buttonContainer, SWT.PUSH); fSelectAllButton.setText(Messages.getString("NewTestSuiteWizPage.selectAll")); //$NON-NLS-1$ GridData bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fSelectAllButton.setLayoutData(bgd); fSelectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fClassesInSuiteTable.setAllChecked(true); handleFieldChanged(CLASSES_IN_SUITE); } }); fDeselectAllButton= new Button(buttonContainer, SWT.PUSH); fDeselectAllButton.setText(Messages.getString("NewTestSuiteWizPage.deselectAll")); //$NON-NLS-1$ bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fDeselectAllButton.setLayoutData(bgd); fDeselectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fClassesInSuiteTable.setAllChecked(false); handleFieldChanged(CLASSES_IN_SUITE); } }); // No of selected classes label fSelectedClassesLabel= new Label(parent, SWT.LEFT | SWT.WRAP); fSelectedClassesLabel.setFont(parent.getFont()); updateSelectedClassesLabel(); gd = new GridData(); gd.horizontalSpan = 2; fSelectedClassesLabel.setLayoutData(gd); } } public static class ClassesInSuitContentProvider implements IStructuredContentProvider { private Object[] fTypes; public ClassesInSuitContentProvider() { super(); } public Object[] getElements(Object parent) { try { if (parent instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) parent; ICompilationUnit[] cuArray= pack.getCompilationUnits(); ArrayList typesArrayList= new ArrayList(); for (int i= 0; i < cuArray.length; i++) { ICompilationUnit cu= cuArray[i]; IType[] types= cu.getTypes(); for (int j= 0; j < types.length; j++) { if (TestSearchEngine.isTestImplementor(types[j])) typesArrayList.add(types[j]); } } return typesArrayList.toArray(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } return new Object[0]; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } /* * @see TypePage#evalMethods */ protected void createTypeMembers(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { writeImports(imports); type.createMethod(getSuiteMethodString(), null, false, null); } public String getSuiteMethodString() throws JavaModelException { IPackageFragment pack= getPackageFragment(); String packName= pack.getElementName(); StringBuffer suite= new StringBuffer("public static Test suite () {TestSuite suite= new TestSuite(\"Test for "+((packName.equals(""))?"default package":packName)+"\");\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ suite.append(getUpdatableString()); suite.append("\nreturn suite;}"); //$NON-NLS-1$ return suite.toString(); } public String getUpdatableString() throws JavaModelException { StringBuffer suite= new StringBuffer(); suite.append(startMarker+"\n"); //$NON-NLS-1$ Object[] checkedObjects= fClassesInSuiteTable.getCheckedElements(); for (int i= 0; i < checkedObjects.length; i++) { if (checkedObjects[i] instanceof IType) { IType testType= (IType) checkedObjects[i]; IMethod suiteMethod= testType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (!suiteMethod.exists()) { suite.append("suite.addTest(new TestSuite("+testType.getElementName()+".class));"); //$NON-NLS-1$ //$NON-NLS-2$ } else { suite.append("suite.addTest("+testType.getElementName()+".suite());"); //$NON-NLS-1$ //$NON-NLS-2$ } } } suite.append("\n"+endMarker); //$NON-NLS-1$ return suite.toString(); } public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } updateExistingClass(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } protected void updateExistingClass(IProgressMonitor monitor) throws CoreException, InterruptedException { try { IPackageFragment pack= getPackageFragment(); ICompilationUnit cu= pack.getCompilationUnit(getTypeName() + ".java"); //$NON-NLS-1$ if (!cu.exists()) { createType(monitor); fUpdatedExistingClassButton= false; return; } IType suiteType= cu.getType(getTypeName()); monitor.beginTask(Messages.getString("NewTestSuiteWizPage.createType.beginTask"), 10); //$NON-NLS-1$ IMethod suiteMethod= suiteType.getMethod("suite", new String[] {}); //$NON-NLS-1$ monitor.worked(1); String lineDelimiter= JUnitStubUtility.getLineDelimiterUsed(cu); if (suiteMethod.exists()) { ISourceRange range= suiteMethod.getSourceRange(); if (range != null) { IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); StringBuffer source= new StringBuffer(originalContent); //using JDK 1.4 //int start= source.toString().indexOf(startMarker) --> int start= source.indexOf(startMarker); int start= source.toString().indexOf(startMarker); if (start > -1) { //using JDK 1.4 //int end= source.toString().indexOf(endMarker, start) --> int end= source.indexOf(endMarker, start) int end= source.toString().indexOf(endMarker, start); if (end > -1) { monitor.subTask(Messages.getString("NewTestSuiteWizPage.createType.updating.suite_method")); //$NON-NLS-1$ monitor.worked(1); end += endMarker.length(); source.replace(start, end, getUpdatableString()); buf.replace(range.getOffset(), range.getLength(), source.toString()); cu.reconcile(null); originalContent= buf.getText(0, buf.getLength()); monitor.worked(1); String formattedContent= JUnitStubUtility.codeFormat(originalContent, 0, lineDelimiter); buf.replace(0, buf.getLength(), formattedContent); monitor.worked(1); cu.save(new SubProgressMonitor(monitor, 1), false); } else { cannotUpdateSuiteError(); } } else { cannotUpdateSuiteError(); } } else { MessageDialog.openError(getShell(), Messages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.title"), Messages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.message")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { suiteType.createMethod(getSuiteMethodString(), null, true, monitor); ISourceRange range= cu.getSourceRange(); IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); monitor.worked(2); String formattedContent= JUnitStubUtility.codeFormat(originalContent, 0, lineDelimiter); buf.replace(range.getOffset(), range.getLength(), formattedContent); monitor.worked(1); cu.save(new SubProgressMonitor(monitor, 1), false); } monitor.done(); fUpdatedExistingClassButton= true; } catch (JavaModelException e) { JUnitPlugin.log(e); } } public boolean hasUpdatedExistingClass() { return fUpdatedExistingClassButton; } private IStatus classesInSuiteChanged() { JUnitStatus status= new JUnitStatus(); if (fClassesInSuiteTable.getCheckedElements().length <= 0) status.setWarning(Messages.getString("NewTestSuiteWizPage.classes_in_suite.error.no_testclasses_selected")); //$NON-NLS-1$ return status; } private void updateSelectedClassesLabel() { int noOfClassesChecked= fClassesInSuiteTable.getCheckedElements().length; fSelectedClassesLabel.setText(noOfClassesChecked+((noOfClassesChecked==1)?SELECTED_CLASSES_LABEL_TEXT_ONE:SELECTED_CLASSES_LABEL_TEXT_MANY)); } protected void createSuiteNameControl(Composite composite, int nColumns) { fSuiteNameLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fSuiteNameLabel.setFont(composite.getFont()); fSuiteNameLabel.setText(Messages.getString("NewTestSuiteWizPage.suiteName.text")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fSuiteNameLabel.setLayoutData(gd); fSuiteNameText= new Text(composite, SWT.SINGLE | SWT.BORDER); // moved up due to 1GEUNW2 fSuiteNameText.setEnabled(true); fSuiteNameText.setFont(composite.getFont()); fSuiteNameText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(SUITE_NAME); } }); gd= new GridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fSuiteNameText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fSuiteNameText==null)?fSuiteNameTextInitialValue:fSuiteNameText.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { if (fSuiteNameText == null) { fSuiteNameTextInitialValue= name; } else { fSuiteNameText.setText(name); fSuiteNameText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testSuiteChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(Messages.getString("NewTestSuiteWizPage.typeName.error.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(Messages.getString("NewTestSuiteWizPage.typeName.error.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.getString("NewTestSuiteWizPage.typeName.error.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.getString("NewTestSuiteWizPage.typeName.error.name.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setWarning(Messages.getString("NewTestSuiteWizPage.typeName.warning.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * Sets the focus. */ protected void setFocus() { fSuiteNameText.setFocus(); } public void setCheckedElements(Object[] elements) { fClassesInSuiteTable.setCheckedElements(elements); } protected void cannotUpdateSuiteError() { MessageDialog.openError(getShell(), Messages.getString("NewTestSuiteWizPage.cannotUpdateDialog.title"), //$NON-NLS-1$ Messages.getFormattedString("NewTestSuiteWizPage.cannotUpdateDialog.message", new String[] {startMarker, endMarker})); //$NON-NLS-1$ } private void writeImports(IImportsStructure imports) { imports.addImport("junit.framework.Test"); //$NON-NLS-1$ imports.addImport("junit.framework.TestSuite"); //$NON-NLS-1$ } // /** // * Creates a type using the current field values. // */ // public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { // monitor.beginTask(Messages.getString("NewTestSuiteWizPage.createType.beginTask"), 10); //$NON-NLS-1$ // // IPackageFragmentRoot root= getPackageFragmentRoot(); // IPackageFragment pack= getPackageFragment(); // if (pack == null) { // pack= root.getPackageFragment(""); //$NON-NLS-1$ // } // // if (!pack.exists()) { // String packName= pack.getElementName(); // pack= root.createPackageFragment(packName, true, null); // } // // monitor.worked(1); // // String clName= getTypeName(); // // boolean isInnerClass= isEnclosingTypeSelected(); // // IType createdType; // ImportsStructure imports; // int indent= 0; // // String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); // int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); // // String lineDelimiter= null; // // ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$ // // imports= new ImportsStructure(parentCU, prefOrder, threshold, false); // // lineDelimiter= JUnitStubUtility.getLineDelimiterUsed(parentCU); // // String content= createTypeBody(imports, lineDelimiter, parentCU); // createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5)); // // // add imports for superclass/interfaces, so the type can be parsed correctly //// writeImports(imports); // imports.create(true, new SubProgressMonitor(monitor, 1)); // // String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1)); // if (methods.length > 0) { // for (int i= 0; i < methods.length; i++) { // createdType.createMethod(methods[i], null, false, null); // } // // add imports // imports.create(!isInnerClass, null); // } // monitor.worked(1); // // ICompilationUnit cu= createdType.getCompilationUnit(); // ISourceRange range; // if (isInnerClass) { // synchronized(cu) { // cu.reconcile(); // } // range= createdType.getSourceRange(); // } else { // range= cu.getSourceRange(); // } // // IBuffer buf= cu.getBuffer(); // String originalContent= buf.getText(range.getOffset(), range.getLength()); // String formattedContent= JUnitStubUtility.codeFormat(originalContent, indent, lineDelimiter); // buf.replace(range.getOffset(), range.getLength(), formattedContent); // if (!isInnerClass) { // String fileComment= getFileComment(cu); // if (fileComment != null) { // buf.replace(0, 0, fileComment + lineDelimiter); // } // buf.save(new SubProgressMonitor(monitor, 1), false); // } else { // monitor.worked(1); // } // fCreatedType= createdType; // monitor.done(); // } // // /* // * Called from createType to construct the source for this type // */ // private String createTypeBody(IImportsStructure imports, String lineDelimiter, ICompilationUnit parentCU) { // StringBuffer buf= new StringBuffer(); // String typeComment= getTypeComment(parentCU); // if (typeComment != null) { // buf.append(typeComment); // buf.append(lineDelimiter); // } // // int modifiers= getModifiers(); // buf.append(Flags.toString(modifiers)); // if (modifiers != 0) { // buf.append(' '); // } // buf.append("class "); //$NON-NLS-1$ // buf.append(getTypeName()); // buf.append(" {"); //$NON-NLS-1$ // buf.append(lineDelimiter); // buf.append(lineDelimiter); // buf.append('}'); // buf.append(lineDelimiter); // return buf.toString(); // } // // public IType getCreatedType() { // return fCreatedType; // } }
11,689
Bug 11689 NPE creating a test case in empty workbench
If you create a project and then a JUnit TestCase when there are no other classes in the image you will get a NullPointerException when you select the browse button on the Test Class entry. STEPS 1) Create a ConfigurableProject 2) Create a JUnit Test class. In the creation dialog select the 3rd browse button. Walkback: java.lang.NullPointerException at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.chooseClassToTestTyp e(NewTestCaseCreationWizardPage.java:318) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.classToTestButtonPre ssed(NewTestCaseCreationWizardPage.java:293) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage.access$0 (NewTestCaseCreationWizardPage.java:292) at org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizardPage$3.widgetSelected (NewTestCaseCreationWizardPage.java:279) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.actions.NewWizardAction.run(NewWizardAction.java:74) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:698) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
resolved fixed
4f1a191
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-27T10:34:12Z
2002-03-19T20:33:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/wizards/UpdateTestSuite.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ package org.eclipse.jdt.junit.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.*; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; /** * An object contribution action that updates existing AllTests classes. */ public class UpdateTestSuite implements IObjectActionDelegate { private Shell fShell; private IPackageFragment fPack; private ICompilationUnit fTestSuite; private IMethod fSuiteMethod; private static boolean fEmptySelectionAllowed= false; private Object[] fSelectedTestCases; private class UpdateAllTestsValidator implements ISelectionValidator { /* * @see ISelectionValidator#validate(Object[]) */ public IStatus validate(Object[] selection) { int count= 0; for (int i= 0; i < selection.length; i++) { if (selection[i] instanceof IType) { count++; } } if (count == 0 && !fEmptySelectionAllowed) { return new JUnitStatus(IStatus.ERROR, ""); //$NON-NLS-1$ } String message; if (count == 1) { message= Messages.getFormattedString("UpdateAllTests.selected_methods.label_one", new Integer(count)); //$NON-NLS-1$ } else { message= Messages.getFormattedString("UpdateAllTests.selected_methods.label_many", new Integer(count)); //$NON-NLS-1$ } return new JUnitStatus(IStatus.INFO, message); } } public UpdateTestSuite() { super(); } /* * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { } /* * @see IActionDelegate#run(IAction) */ public void run(IAction action) { ILabelProvider lprovider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); IStructuredContentProvider cprovider= new NewTestSuiteCreationWizardPage.ClassesInSuitContentProvider(); /* find TestClasses already in Test Suite */ IType testSuiteType= JavaModelUtil.findPrimaryType(fTestSuite); fSuiteMethod= testSuiteType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (fSuiteMethod.exists()) { try { ISourceRange range= fSuiteMethod.getSourceRange(); IBuffer buf= fTestSuite.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); buf.close(); int start= originalContent.indexOf(NewTestSuiteCreationWizardPage.startMarker); if (start > -1) { if (originalContent.indexOf(NewTestSuiteCreationWizardPage.endMarker, start) > -1) { CheckedTableSelectionDialog dialog= new CheckedTableSelectionDialog(fShell, lprovider, cprovider); dialog.setValidator(new UpdateAllTestsValidator()); dialog.setTitle(Messages.getString("UpdateAllTests.title")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("UpdateAllTests.message")); //$NON-NLS-1$ dialog.setInitialSelections(cprovider.getElements(fPack)); dialog.setSize(60, 25); dialog.setInput(fPack); if (dialog.open() == dialog.OK) { fSelectedTestCases= dialog.getResult(); ProgressMonitorDialog progressDialog= new ProgressMonitorDialog(fShell); try { progressDialog.run(false, false, getRunnable()); } catch (Exception e) { JUnitPlugin.log(e); } } } else { cannotUpdateSuiteError(); } } else { cannotUpdateSuiteError(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } else { noSuiteError(); } } /* * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { fShell= JUnitPlugin.getActiveWorkbenchShell(); if (selection instanceof IStructuredSelection) { Object testSuiteObj= ((IStructuredSelection) selection).getFirstElement(); if (testSuiteObj != null && testSuiteObj instanceof ICompilationUnit) { fTestSuite= (ICompilationUnit) testSuiteObj; IJavaElement packIJE= fTestSuite.getParent(); if (packIJE instanceof IPackageFragment) { fPack= (IPackageFragment) packIJE; } } } } private void updateTestCasesInSuite(IProgressMonitor monitor) { try { monitor.beginTask(Messages.getString("UpdateAllTests.beginTask"), 5); //$NON-NLS-1$ ISourceRange range= fSuiteMethod.getSourceRange(); IBuffer buf= fTestSuite.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); StringBuffer source= new StringBuffer(originalContent); //using JDK 1.4 //int start= source.toString().indexOf(NewTestSuiteCreationWizardPage.startMarker) --> int start= source.indexOf(NewTestSuiteCreationWizardPage.startMarker) int start= source.toString().indexOf(NewTestSuiteCreationWizardPage.startMarker); if (start > -1) { //using JDK 1.4 //int end= source.toString().indexOf(NewTestSuiteCreationWizardPage.endMarker, start) --> int end= source.indexOf(NewTestSuiteCreationWizardPage.endMarker, start) int end= source.toString().indexOf(NewTestSuiteCreationWizardPage.endMarker, start); if (end > -1) { monitor.worked(1); end += NewTestSuiteCreationWizardPage.endMarker.length(); // String updatableCode= source.substring(start,end+NewTestSuiteCreationWizardPage.endMarker.length()); source.replace(start, end, getUpdatableString()); buf.replace(range.getOffset(), range.getLength(), source.toString()); monitor.worked(1); fTestSuite.reconcile(null); originalContent= buf.getText(0, buf.getLength()); monitor.worked(1); String formattedContent= JUnitStubUtility.codeFormat( originalContent, 0, JUnitStubUtility.getLineDelimiterUsed(fTestSuite)); //buf.replace(range.getOffset(), range.getLength(), formattedContent); buf.replace(0, buf.getLength(), formattedContent); monitor.worked(1); fTestSuite.save(new SubProgressMonitor(monitor, 1), true); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } updateTestCasesInSuite(monitor); } }; } public String getUpdatableString() throws JavaModelException { StringBuffer suite= new StringBuffer(); suite.append(NewTestSuiteCreationWizardPage.startMarker+"\n"); //$NON-NLS-1$ for (int i= 0; i < fSelectedTestCases.length; i++) { if (fSelectedTestCases[i] instanceof IType) { IType testType= (IType) fSelectedTestCases[i]; IMethod suiteMethod= testType.getMethod("suite", new String[] {}); //$NON-NLS-1$ if (!suiteMethod.exists()) { suite.append("suite.addTest(new TestSuite("+testType.getElementName()+".class));"); //$NON-NLS-1$ //$NON-NLS-2$ } else { suite.append("suite.addTest("+testType.getElementName()+".suite());"); //$NON-NLS-1$ //$NON-NLS-2$ } } } suite.append("\n"+NewTestSuiteCreationWizardPage.endMarker); //$NON-NLS-1$ return suite.toString(); } private void cannotUpdateSuiteError() { MessageDialog.openError(fShell, Messages.getString("UpdateAllTests.cannotUpdate.errorDialog.title"), //$NON-NLS-1$ Messages.getFormattedString("UpdateAllTests.cannotUpdate.errorDialog.message", new String[] {NewTestSuiteCreationWizardPage.startMarker, NewTestSuiteCreationWizardPage.endMarker})); //$NON-NLS-1$ } private void noSuiteError() { MessageDialog.openError(fShell, Messages.getString("UpdateAllTests.cannotFind.errorDialog.title"), Messages.getString("UpdateAllTests.cannotFind.errorDialog.message")); //$NON-NLS-1$ //$NON-NLS-2$ } }
10,888
Bug 10888 Refactoring - move add redundant import statements
Build 20020305 Having the following setup: Project +- src folder +- p1 +- X.java [package p1; class X{}] +- p2 +- Y.java [package p2; import p1.X; class Y extends X {}] +- p3 Then move 'X' from 'p1' to 'p3' and request to update references to X. At the end, Y.java source is unoptimal: package p2; import p3.*; // ??? import p3.X; public class Y extends X { }
resolved fixed
b1c08d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-27T16:59:08Z
2002-03-06T18:40:00Z
org.eclipse.jdt.ui/core
10,888
Bug 10888 Refactoring - move add redundant import statements
Build 20020305 Having the following setup: Project +- src folder +- p1 +- X.java [package p1; class X{}] +- p2 +- Y.java [package p2; import p1.X; class Y extends X {}] +- p3 Then move 'X' from 'p1' to 'p3' and request to update references to X. At the end, Y.java source is unoptimal: package p2; import p3.*; // ??? import p3.X; public class Y extends X { }
resolved fixed
b1c08d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-27T16:59:08Z
2002-03-06T18:40:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveCuUpdateCreator.java
12,336
Bug 12336 Java Browsing views get cleared in combination with type hierarchy
1. Add Type Hierarchy view to Java Browsing perspective 2. Select a type in the type hierarchy ==> Java Browsing views show correct state 3. Click on a Java Browsing view "Types" or "Packages" ==> Java Browsing views get cleared.
resolved fixed
a91b4fa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T11:52:07Z
2002-03-27T09:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/SelectionProviderMediator.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; /** * A selection provider for viewparts with more that one viewer. * Tracks the focus of the viewers to provide the correct selection. */ public class SelectionProviderMediator implements ISelectionProvider { private class InternalListener implements ISelectionChangedListener, FocusListener { /* * @see ISelectionChangedListener#selectionChanged */ public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } /* * @see FocusListener#focusGained */ public void focusGained(FocusEvent e) { doFocusChanged(e.widget); } /* * @see FocusListener#focusLost */ public void focusLost(FocusEvent e) { propagateFocusChanged(null); } } private Viewer[] fViewers; private InternalListener fListener; private Viewer fViewerInFocus; private ListenerList fSelectionChangedListeners; /** * @param All viewers that can provide a selection */ public SelectionProviderMediator(Viewer[] viewers) { Assert.isNotNull(viewers); fViewers= viewers; fListener= new InternalListener(); fSelectionChangedListeners= new ListenerList(4); fViewerInFocus= null; for (int i= 0; i < fViewers.length; i++) { Viewer viewer= fViewers[i]; viewer.addSelectionChangedListener(fListener); Control control= viewer.getControl(); control.addFocusListener(fListener); } } private void doFocusChanged(Widget control) { for (int i= 0; i < fViewers.length; i++) { if (fViewers[i].getControl() == control) { propagateFocusChanged(fViewers[i]); return; } } } private void doSelectionChanged(SelectionChangedEvent event) { ISelectionProvider provider= event.getSelectionProvider(); if (provider == fViewerInFocus) { fireSelectionChanged(); } } private void propagateFocusChanged(Viewer viewer) { if (viewer != fViewerInFocus) { // Ok to compare by idendity fViewerInFocus= viewer; fireSelectionChanged(); } } private void fireSelectionChanged() { if (fSelectionChangedListeners != null) { SelectionChangedEvent event= new SelectionChangedEvent(this, getSelection()); Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { ISelectionChangedListener listener= (ISelectionChangedListener) listeners[i]; listener.selectionChanged(event); } } } /* * @see ISelectionProvider#addSelectionChangedListener */ public void addSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.add(listener); } /* * @see ISelectionProvider#removeSelectionChangedListener */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.remove(listener); } /* * @see ISelectionProvider#getSelection */ public ISelection getSelection() { if (fViewerInFocus != null) { return fViewerInFocus.getSelection(); } else { return StructuredSelection.EMPTY; } } /* * @see ISelectionProvider#setSelection */ public void setSelection(ISelection selection) { if (fViewerInFocus != null) { fViewerInFocus.setSelection(selection); } } /** * Returns the viewer in focus or null if no viewer has the focus */ public Viewer getViewerInFocus() { return fViewerInFocus; } }
10,403
Bug 10403 Project creation should confirm the bin directory can be scrubbed
When a user creates a new project for an existing directory structure, we should confirm that the output directory can be deleted then rebuilt. Some users are creating projects & pointing the output folder at a bin directory which contains more than just .class files which can be rebuilt from the available .java files.
resolved fixed
7007de3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T12:14:00Z
2002-02-27T17:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; 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.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; public class BuildPathsBlock { private IWorkspaceRoot fWorkspaceRoot; private CheckedListDialogField fClassPathList; private StringButtonDialogField fBuildPathDialogField; private StatusInfo fClassPathStatus; private StatusInfo fBuildPathStatus; private IJavaProject fCurrJProject; private IPath fOutputLocationPath; private IStatusChangeListener fContext; private Control fSWTWidget; private boolean fShowSourceFolderPage; private SourceContainerWorkbookPage fSourceContainerPage; private ProjectsWorkbookPage fProjectsPage; private LibrariesWorkbookPage fLibrariesPage; private BuildPathBasePage fCurrPage; public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean showSourceFolders) { fWorkspaceRoot= root; fContext= context; fShowSourceFolderPage= showSourceFolders; fSourceContainerPage= null; fLibrariesPage= null; fProjectsPage= null; fCurrPage= null; BuildPathAdapter adapter= new BuildPathAdapter(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$ }; fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fClassPathList.setDialogFieldListener(adapter); fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); fClassPathList.setUpButtonIndex(0); fClassPathList.setDownButtonIndex(1); fClassPathList.setCheckAllButtonIndex(3); fClassPathList.setUncheckAllButtonIndex(4); fBuildPathDialogField= new StringButtonDialogField(adapter); fBuildPathDialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$ fBuildPathDialogField.setDialogFieldListener(adapter); fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$ fBuildPathStatus= new StatusInfo(); fClassPathStatus= new StatusInfo(); fCurrJProject= null; } // -------- UI creation --------- public Control createControl(Composite parent) { fSWTWidget= parent; PixelConverter converter= new PixelConverter(parent); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.numColumns= 1; composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); folder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabChanged(e.item); } }); ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry(); TabItem item; fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT)); item.setData(fSourceContainerPage); item.setControl(fSourceContainerPage.getControl(folder)); IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); fProjectsPage= new ProjectsWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$ item.setImage(projectImage); item.setData(fProjectsPage); item.setControl(fProjectsPage.getControl(folder)); fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY)); item.setData(fLibrariesPage); item.setControl(fLibrariesPage.getControl(folder)); // a non shared image Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage(); composite.addDisposeListener(new ImageDisposer(cpoImage)); ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$ item.setImage(cpoImage); item.setData(ordpage); item.setControl(ordpage.getControl(folder)); if (fCurrJProject != null) { fSourceContainerPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); } Composite editorcomp= new Composite(composite, SWT.NONE); DialogField[] editors= new DialogField[] { fBuildPathDialogField }; LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0); int maxFieldWidth= converter.convertWidthInCharsToPixels(40); LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth); LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null)); editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if (fShowSourceFolderPage) { folder.setSelection(0); fCurrPage= fSourceContainerPage; } else { folder.setSelection(3); fCurrPage= ordpage; fClassPathList.selectFirstElement(); } WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Initializes the classpath for the given project. Multiple calls to init are allowed, * but all existing settings will be cleared and replace by the given or default paths. * @param project The java project to configure. Does not have to exist. * @param outputLocation The output location to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project- the * output location of the existing project * @param classpathEntries The classpath entries to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * classpath entries of the existing project */ public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) { fCurrJProject= jproject; boolean projExists= false; try { IProject project= fCurrJProject.getProject(); projExists= (project.exists() && project.getFile(".classpath").exists()); if (projExists) { if (outputLocation == null) { outputLocation= fCurrJProject.getOutputLocation(); } if (classpathEntries == null) { classpathEntries= fCurrJProject.getRawClasspath(); } } } catch (CoreException e) { JavaPlugin.log(e.getStatus()); } if (outputLocation == null) { outputLocation= getDefaultBuildPath(jproject); } List newClassPath; if (classpathEntries == null) { newClassPath= getDefaultClassPath(jproject); } else { newClassPath= new ArrayList(); for (int i= 0; i < classpathEntries.length; i++) { IClasspathEntry curr= classpathEntries[i]; int entryKind= curr.getEntryKind(); IPath path= curr.getPath(); boolean isExported= curr.isExported(); // get the resource IResource res= null; boolean isMissing= false; if (entryKind != IClasspathEntry.CPE_VARIABLE) { res= fWorkspaceRoot.findMember(path); if (res == null) { isMissing= (entryKind != IClasspathEntry.CPE_LIBRARY || !path.toFile().isFile()); } } else { IPath resolvedPath= JavaCore.getResolvedVariablePath(path); isMissing= (resolvedPath == null) || !resolvedPath.toFile().isFile(); } CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported); if (projExists) { elem.setIsMissing(isMissing); } newClassPath.add(elem); } } List exportedEntries = new ArrayList(); for (int i= 0; i < newClassPath.size(); i++) { CPListElement curr= (CPListElement) newClassPath.get(i); if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { exportedEntries.add(curr); } } // inits the dialog field fBuildPathDialogField.setText(outputLocation.makeRelative().toString()); fClassPathList.setElements(newClassPath); fClassPathList.setCheckedElements(exportedEntries); if (fSourceContainerPage != null) { fSourceContainerPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); } doStatusLineUpdate(); } // -------- public api -------- /** * Returns the Java project. Can return <code>null<code> if the page has not * been initialized. */ public IJavaProject getJavaProject() { return fCurrJProject; } /** * Returns the current output location. Note that the path returned must not be valid. */ public IPath getOutputLocation() { return new Path(fBuildPathDialogField.getText()).makeAbsolute(); } /** * Returns the current class path (raw). Note that the entries returned must not be valid. */ public IClasspathEntry[] getRawClassPath() { List elements= fClassPathList.getElements(); int nElements= elements.size(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= 0; i < nElements; i++) { CPListElement currElement= (CPListElement) elements.get(i); entries[i]= currElement.getClasspathEntry(); } return entries; } // -------- evaluate default settings -------- private List getDefaultClassPath(IJavaProject jproj) { List list= new ArrayList(); IResource srcFolder; if (JavaBasePreferencePage.useSrcAndBinFolders()) { String sourceFolderName= JavaBasePreferencePage.getSourceFolderName(); srcFolder= jproj.getProject().getFolder(sourceFolderName); } else { srcFolder= jproj.getProject(); } list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder)); IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE); IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE); IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE); CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false); list.add(elem); return list; } private IPath getDefaultBuildPath(IJavaProject jproj) { if (JavaBasePreferencePage.useSrcAndBinFolders()) { String outputLocationName= JavaBasePreferencePage.getOutputLocationName(); return jproj.getProject().getFullPath().append(outputLocationName); } else { return jproj.getProject().getFullPath(); } } private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { buildPathChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { buildPathDialogFieldChanged(field); } } private void buildPathChangeControlPressed(DialogField field) { if (field == fBuildPathDialogField) { IContainer container= chooseContainer(); if (container != null) { fBuildPathDialogField.setText(container.getFullPath().toString()); } } } private void buildPathDialogFieldChanged(DialogField field) { if (field == fClassPathList) { updateClassPathStatus(); updateBuildPathStatus(); } else if (field == fBuildPathDialogField) { updateBuildPathStatus(); } doStatusLineUpdate(); } // -------- verification ------------------------------- private void doStatusLineUpdate() { IStatus res= findMostSevereStatus(); fContext.statusChanged(res); } private IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus); } /** * Validates the build path. */ private void updateClassPathStatus() { fClassPathStatus.setOK(); List elements= fClassPathList.getElements(); boolean entryMissing= false; IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); boolean isChecked= fClassPathList.isChecked(currElement); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!isChecked) { fClassPathList.setCheckedWithoutUpdate(currElement, true); } } else { currElement.setExported(isChecked); } entries[i]= currElement.getClasspathEntry(); entryMissing= entryMissing || currElement.isMissing(); } if (entryMissing) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$ } if (fCurrJProject.hasClasspathCycle(entries)) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$ } } /** * Validates output location & build path. */ private void updateBuildPathStatus() { fOutputLocationPath= null; String text= fBuildPathDialogField.getText(); if ("".equals(text)) { //$NON-NLS-1$ fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$ return; } IPath path= getOutputLocation(); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { // if exists, must be a folder or project if (res.getType() == IResource.FILE) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$ return; } } fOutputLocationPath= path; List elements= fClassPathList.getElements(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); entries[i]= currElement.getClasspathEntry(); } IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path); if (!status.isOK()) { fBuildPathStatus.setError(status.getMessage()); return; } fBuildPathStatus.setOK(); } // -------- creation ------------------------------- /** * Creates a runnable that sets the configured build paths. */ public IRunnableWithProgress getRunnable() { final List classPathEntries= fClassPathList.getElements(); final IPath path= getOutputLocation(); return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 10); //$NON-NLS-1$ try { createJavaProject(classPathEntries, path, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; } /** * Creates the Java project and sets the configured build path and output location. * If the project already exists only build paths are updated. */ private void createJavaProject(List classPathEntries, IPath buildPath, IProgressMonitor monitor) throws CoreException { // 10 monitor steps to go // create and set the output path first if (!fWorkspaceRoot.exists(buildPath)) { IFolder folder= fWorkspaceRoot.getFolder(buildPath); CoreUtility.createFolder(folder, true, true, null); } monitor.worked(2); int nEntries= classPathEntries.size(); IClasspathEntry[] classpath= new IClasspathEntry[nEntries]; // create and set the class path for (int i= 0; i < nEntries; i++) { CPListElement entry= ((CPListElement)classPathEntries.get(i)); IResource res= entry.getResource(); if ((res instanceof IFolder) && !res.exists()) { CoreUtility.createFolder((IFolder)res, true, true, null); } classpath[i]= entry.getClasspathEntry(); // set javadoc location URL javadocLocation= entry.getJavadocLocation(); if (javadocLocation != null) { IPath path= entry.getPath(); if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { path= JavaCore.getResolvedVariablePath(path); } if (path != null) { JavaDocLocations.setLibraryJavadocLocation(path, javadocLocation); } } } monitor.worked(1); fCurrJProject.setRawClasspath(classpath, buildPath, new SubProgressMonitor(monitor, 7)); } // ---------- util method ------------ private IContainer chooseContainer() { Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); IProject[] allProjects= fWorkspaceRoot.getProjects(); ArrayList rejectedElements= new ArrayList(allProjects.length); IProject currProject= fCurrJProject.getProject(); for (int i= 0; i < allProjects.length; i++) { if (!allProjects[i].equals(currProject)) { rejectedElements.add(allProjects[i]); } } ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSelection= null; if (fOutputLocationPath != null) { initSelection= fWorkspaceRoot.findMember(fOutputLocationPath); } ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$ dialog.setValidator(validator); dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSelection); if (dialog.open() == dialog.OK) { return (IContainer)dialog.getFirstResult(); } return null; } // -------- tab switching ---------- private void tabChanged(Widget widget) { if (widget instanceof TabItem) { BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData(); if (fCurrPage != null) { List selection= fCurrPage.getSelection(); if (!selection.isEmpty()) { newPage.setSelection(selection); } } fCurrPage= newPage; } } }
10,458
Bug 10458 Support DND to set focus in Hierarchy View
Please enable Hierarchy view to support DND as a way to "focus on" something, whether it be a project, source folder, package, or type.
resolved fixed
bc9934a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T14:04:37Z
2002-02-28T04:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyTransferDropAdapter.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction; import org.eclipse.jdt.internal.ui.dnd.JdtViewerDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; public class TypeHierarchyTransferDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener { private AddMethodStubAction fAddMethodStubAction; public TypeHierarchyTransferDropAdapter(AbstractTreeViewer viewer) { super(viewer, DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL); fAddMethodStubAction= new AddMethodStubAction(); } //---- TransferDropTargetListener interface --------------------------------------- public Transfer getTransfer() { return LocalSelectionTransfer.getInstance(); } //---- Actual DND ----------------------------------------------------------------- public void validateDrop(Object target, DropTargetEvent event, int operation) { event.detail= DND.DROP_NONE; ISelection selection= LocalSelectionTransfer.getInstance().getSelection(); if (target instanceof IType) { if (AddMethodStubAction.canActionBeAdded((IType)target, selection)) { if (operation == DND.DROP_NONE) { operation= DND.DROP_COPY; // use copy as default operation } event.detail= operation; } } return; } public void drop(Object target, DropTargetEvent event) { ISelection selection= LocalSelectionTransfer.getInstance().getSelection(); if (target instanceof IType) { if (fAddMethodStubAction.init((IType)target, selection)) { fAddMethodStubAction.run(); } } return; } }
10,458
Bug 10458 Support DND to set focus in Hierarchy View
Please enable Hierarchy view to support DND as a way to "focus on" something, whether it be a project, source folder, package, or type.
resolved fixed
bc9934a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T14:04:37Z
2002-02-28T04:20: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.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; 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.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.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.IInputSelectionProvider; 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.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.PageBook; 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.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; 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.ContextMenuGroup; import org.eclipse.jdt.internal.ui.dnd.BasicSelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.BuildGroup; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; 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 { 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$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of inut elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private IProblemChangedListener fHierarchyProblemListener; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private MethodsViewer fMethodsViewer; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private boolean fIsEnableMemberFilter; 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 IDialogSettings fDialogSettings; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private int fCurrentOrientation; private EnableMemberFilterAction fEnableMemberFilterAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private IPartListener fPartListener; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fHierarchyProblemListener= null; 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); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); 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) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; } /** * 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) { ICompilationUnit cu= member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { member= (IMember) cu.getOriginal(member); if (member == null) { return; } } if (member.getElementType() != IJavaElement.TYPE) { Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { methodControl.setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } else { Control viewerControl= getCurrentViewer().getControl(); if (viewerControl != null && !viewerControl.isDisposed()) { viewerControl.setFocus(); } 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) { 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")); return; } } if (element.getElementType() == IJavaElement.METHOD || element.getElementType() == IJavaElement.FIELD || element.getElementType() == IJavaElement.INITIALIZER) { element= ((IMember) element).getDeclaringType(); } } } 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; fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e); clearInput(); return; } fPagebook.showPage(fTypeMethodsSplitter); if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } IType root= getSelectableType(fInputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); } } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); getSite().getPage().removePartListener(fPartListener); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } if (fMethodsViewer != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fMethodsViewer); } super.dispose(); } 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.F4) { OpenTypeHierarchyUtil.open(getSite().getSelectionProvider().getSelection(), getSite().getWorkbenchWindow()); return; } else if (event.keyCode == SWT.F5) { updateHierarchyViewer(); 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); } 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()); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fMethodsViewer); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_COPY; DragSource source= new DragSource(fMethodsViewer.getControl(), ops); source.setTransfer(transfers); source.addDragListener(new BasicSelectionTransferDragAdapter(fMethodsViewer)); for (int i= 0; i < fAllViewers.length; i++) { TypeHierarchyViewer curr= fAllViewers[i]; curr.addDropSupport(ops, transfers, new TypeHierarchyTransferDropAdapter(curr)); } } 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); initDragAndDrop(); 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); // 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)); // 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); } ReorgGroup.addGlobalReorgActions(getViewSite().getActionBars(), getViewSite().getSelectionProvider()); WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); } /** * 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); // viewer entries viewer.contributeToContextMenu(menu); IStructuredSelection selection= (IStructuredSelection)viewer.getSelection(); if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { addOpenPerspectiveItem(menu, selection); } addOpenWithMenu(menu, selection); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnTypeAction); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnSelectionAction); addRefactoring(menu, viewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, viewer); } /** * 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); } //menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer)); addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection()); addRefactoring(menu, fMethodsViewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, fMethodsViewer); } private void addRefactoring(IMenuManager menu, IInputSelectionProvider viewer){ MenuManager refactoring= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.refactor")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, viewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IJavaElement)) return; IResource resource= null; try { resource= ((IJavaElement)element).getUnderlyingResource(); } catch(JavaModelException e) { // ignore } if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } private void addOpenPerspectiveItem(IMenuManager menu, IStructuredSelection selection) { OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, selection); } /** * 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) { ISelection sel= null; if (elem.getElementType() != IJavaElement.TYPE) { return (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); } private void internalSelectMember(IMember member) { fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener); fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY); fMethodsViewer.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() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); // 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(IType input) { if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } fMethodsViewer.setInput(input); } } private void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); } else { typeSelectionChanged(e.getSelection()); } } private void methodSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (fIsEnableMemberFilter) { IMember[] memberFilter= null; if (nSelected > 0) { memberFilter= new IMember[nSelected]; selected.toArray(memberFilter); } setMemberFilter(memberFilter); updateHierarchyViewer(); 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)) { try { getSite().getPage().removePartListener(fPartListener); EditorUtility.openInEditor(elem, false); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } catch (CoreException e) { JavaPlugin.log(e); } } } 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(); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { internalSelectType(getSelectableType(fInputElement), false); currSelection= getCurrentViewer().getSelection(); } if (!fIsEnableMemberFilter) { typeSelectionChanged(currSelection); } } updateTitle(); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } fHierarchyProblemListener= getCurrentViewer(); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fHierarchyProblemListener); 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(); 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 ITypeHierarchyLifeCycleListener. * Can be called from any thread */ private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { doTypeHierarchyChangedOnViewers(changedTypes); } }); } } private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } updateHierarchyViewer(); } else { // elements in hierarchy modified if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } fMethodsViewer.refresh(); } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { return (IJavaElement) input; } 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) { memento.putString(TAG_INPUT, fInputElement.getHandleIdentifier()); } 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); } /** * 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.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); if (selectionId != null) { IJavaElement elem= JavaCore.create(selectionId); if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) { internalSelectType((IMember)elem, false); } } fMethodsViewer.restoreState(memento); } /** * Link selection to active editor. */ private void editorActivated(IEditorPart editor) { if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) { 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.getStatus()); } } }
10,458
Bug 10458 Support DND to set focus in Hierarchy View
Please enable Hierarchy view to support DND as a way to "focus on" something, whether it be a project, source folder, package, or type.
resolved fixed
bc9934a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T14:04:37Z
2002-02-28T04:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/OpenTypeHierarchyUtil.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.util; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.core.runtime.CoreException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveRegistry; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPreferenceConstants; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.internal.WorkbenchPlugin; 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.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.actions.OpenHierarchyAction; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaUI; public class OpenTypeHierarchyUtil { private OpenTypeHierarchyUtil() { } public static boolean canOperateOn(ISelection s) { Object element= getElement(s); return (element != null) ? (getCandidates(element) != null) : false; } public static void addToMenu(IWorkbenchWindow window, IMenuManager menu, ISelection s) { addToMenu(window, menu, getElement(s)); } public static void addToMenu(IWorkbenchWindow window, IMenuManager menu, Object element) { IJavaElement[] candidates= getCandidates(element); if (candidates != null) { menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, new OpenHierarchyAction(window, candidates)); } } public static TypeHierarchyViewPart open(ISelection selection, IWorkbenchWindow window) { Object element= getElement(selection); if (element instanceof IJavaElement) { return open((IJavaElement)element, window); } return null; } public static TypeHierarchyViewPart open(IJavaElement element, IWorkbenchWindow window) { IJavaElement[] candidates= getCandidates(element); if (candidates != null) { return open(candidates, window); } return null; } public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) { return open(candidates, window, 0); } public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window, int mask) { Assert.isTrue(candidates != null && candidates.length != 0); IJavaElement input= null; if (candidates.length > 1) { input= selectCandidate(candidates, window.getShell()); } else { input= candidates[0]; } if (input == null) return null; try { if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { return openInPerspective(window, input, mask); } else { return openInViewPart(window, input); } } catch (WorkbenchException e) { JavaPlugin.log(e); MessageDialog.openError(window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$ e.getMessage()); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); MessageDialog.openError(window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$ e.getMessage()); } return null; } private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) { IWorkbenchPage page= window.getActivePage(); try { // 1GEUMSG: ITPJUI:WINNT - Class hierarchy not shown when fast view if (input instanceof IMember) { openEditor(input); } TypeHierarchyViewPart result= (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); result.setInputElement(input); if (input instanceof IMember) { result.selectMember((IMember) input); } return result; } catch (CoreException e) { JavaPlugin.log(e.getStatus()); MessageDialog.openError(window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$ } return null; } private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement input, int mask) throws WorkbenchException, JavaModelException { IPreferenceStore store= WorkbenchPlugin.getDefault().getPreferenceStore(); String mode= store.getString(IWorkbenchPreferenceConstants.OPEN_NEW_PERSPECTIVE); IWorkbenchPage page= null; if (IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_WINDOW.equals(mode)) { page= openWindow(input, mask); } else if (IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_PAGE.equals(mode)) { page= openPage(window, input, mask); } if (input instanceof IMember) { openEditor(input); } return (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); } private static void openEditor(Object input) throws PartInitException, JavaModelException { IEditorPart part= EditorUtility.openInEditor(input, true); if (input instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) input); } private static IWorkbenchPage openWindow(IJavaElement input, int mask) throws WorkbenchException, JavaModelException { return PlatformUI.getWorkbench().openPage(JavaUI.ID_HIERARCHYPERSPECTIVE, input, mask); } private static IWorkbenchPage openPage(IWorkbenchWindow window, IJavaElement input, int mask) throws WorkbenchException, JavaModelException { IWorkbenchPage page= null; /* * not implementable in the current form. See http://dev.eclipse.org/bugs/show_bug.cgi?id=3962 if (JavaBasePreferencePage.reusePerspectiveForTypeHierarchy()) { page= findPage(window); if (page != null) { window.setActivePage(page); TypeHierarchyViewPart part= (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); if (input instanceof IType) part.setInputElement((IType)input); } } */ if (page == null) { page= PlatformUI.getWorkbench().openPage(JavaUI.ID_HIERARCHYPERSPECTIVE, input, mask); } return page; } private static IWorkbenchPage findPage(IWorkbenchWindow window) { IPerspectiveRegistry registry= PlatformUI.getWorkbench().getPerspectiveRegistry(); IPerspectiveDescriptor pd= registry.findPerspectiveWithId(JavaUI.ID_HIERARCHYPERSPECTIVE); IWorkbenchPage pages[]= window.getPages(); for (int i= 0; i < pages.length; i++) { IWorkbenchPage page= pages[i]; if (page.getPerspective().equals(pd)) return page; } return null; } private static IJavaElement selectCandidate(IJavaElement[] candidates, Shell shell) { int flags= (JavaElementLabelProvider.SHOW_DEFAULT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaElementLabelProvider(flags)); dialog.setTitle(JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title")); //$NON-NLS-1$ dialog.setMessage(JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message")); //$NON-NLS-1$ dialog.setElements(candidates); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); if ((elements != null) && (elements.length == 1)) return (IJavaElement) elements[0]; } return null; } private static Object getElement(ISelection s) { if (!(s instanceof IStructuredSelection)) return null; IStructuredSelection selection= (IStructuredSelection)s; if (selection.size() != 1) return null; return selection.getFirstElement(); } /** * Converts the input to a possible input candidates */ private static IJavaElement[] getCandidates(Object input) { if (!(input instanceof IJavaElement)) { return null; } try { IJavaElement elem= (IJavaElement) input; switch (elem.getElementType()) { case IJavaElement.INITIALIZER: case IJavaElement.METHOD: case IJavaElement.FIELD: case IJavaElement.TYPE: case IJavaElement.PACKAGE_FRAGMENT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.JAVA_PROJECT: return new IJavaElement[] { elem }; case IJavaElement.CLASS_FILE: return new IJavaElement[] { ((IClassFile)input).getType() }; case IJavaElement.COMPILATION_UNIT: case IJavaElement.IMPORT_CONTAINER: case IJavaElement.IMPORT_DECLARATION: case IJavaElement.PACKAGE_DECLARATION: { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT); if (cu != null) { IType[] types= cu.getTypes(); if (types.length > 0) { return types; } } break; } default: } } catch (JavaModelException e) { JavaPlugin.log(e); } return null; } }
11,801
Bug 11801 No type completion in @see javadoc tag
20020319 When defining an ICompletionRequestor (org.eclipse.jdt.core) adapter, I could not get completion onto the @see tag in the leading javadoc comment (@see ICompletionRequestor). [package org.eclipse.jdt.core; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.jdt.core.compiler.IProblem; /** * Adapter of the requestor interface <code>ICompletionRequestor</code>. * * @see ICompletionRequestor * @since 2.0 */ public class CompletionRequestorAdapter implements ICompletionRequestor { } ]
resolved fixed
73529a3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T15:46:18Z
2002-03-20T10:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/CompletionEvaluator.java
package org.eclipse.jdt.internal.ui.text.javadoc; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; 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.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.java.ResultCollector; public class CompletionEvaluator { protected final static String[] fgTagProposals= { "@author", //$NON-NLS-1$ "@deprecated", //$NON-NLS-1$ "@exception", //$NON-NLS-1$ "@link", //$NON-NLS-1$ "@param", //$NON-NLS-1$ "@return", //$NON-NLS-1$ "@see", "@serial", "@serialData", "@serialField", "@since", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "@throws", //$NON-NLS-1$ "@version" //$NON-NLS-1$ }; protected final static String[] fgHTMLProposals= { "<code>", "</code>", //$NON-NLS-2$ //$NON-NLS-1$ "<br>", //$NON-NLS-1$ "<b>", "</b>", //$NON-NLS-2$ //$NON-NLS-1$ "<i>", "</i>", //$NON-NLS-2$ //$NON-NLS-1$ "<pre>", "</pre>" //$NON-NLS-2$ //$NON-NLS-1$ }; private ICompilationUnit fCompilationUnit; private IDocument fDocument; private int fCurrentPos; private int fCurrentLength; private JavaElementLabelProvider fLabelProvider; private List fResult; private boolean fRestrictToMatchingCase; public CompletionEvaluator(ICompilationUnit cu, IDocument doc, int pos, int length) { fCompilationUnit= cu; fDocument= doc; fCurrentPos= pos; fCurrentLength= length; fResult= new ArrayList(); fRestrictToMatchingCase= false; fLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_POST_QUALIFIED | JavaElementLabelProvider.SHOW_PARAMETERS); } /** * Tells this evaluator to restrict is proposals to those * starting with matching cases. * * @param restrict <code>true</code> if proposals should be restricted */ public void restrictProposalsToMatchingCases(boolean restrict) { fRestrictToMatchingCase= restrict; } private static boolean isWordPart(char ch) { return Character.isJavaIdentifierPart(ch) || (ch == '#') || (ch == '.') || (ch == '/'); } private static int findCharBeforeWord(IDocument doc, int lineBeginPos, int pos) { int currPos= pos - 1; if (currPos > lineBeginPos) { try { while (currPos > lineBeginPos && isWordPart(doc.getChar(currPos))) { currPos--; } return currPos; } catch (BadLocationException e) { } } return pos; } private static int findLastWhitespace(IDocument doc, int lineBeginPos, int pos) { try { int currPos= pos - 1; while (currPos >= lineBeginPos && Character.isWhitespace(doc.getChar(currPos))) { currPos--; } return currPos + 1; } catch (BadLocationException e) { } return pos; } private static int findClosingCharacter(IDocument doc, int pos, int end, char endChar) throws BadLocationException { int curr= pos; while (curr < end && (doc.getChar(curr) != endChar)) { curr++; } if (curr < end) { return curr + 1; } return pos; } private static int findReplaceEndPos(IDocument doc, String newText, String oldText, int pos) { if (oldText.length() == 0 || oldText.equals(newText)) { return pos; } try { IRegion lineInfo= doc.getLineInformationOfOffset(pos); int end= lineInfo.getOffset() + lineInfo.getLength(); if (newText.endsWith(">")) { //$NON-NLS-1$ // for html, search the tag end character return findClosingCharacter(doc, pos, end, '>'); } else { char ch= 0; int pos1= pos; while (pos1 < end && Character.isJavaIdentifierPart(ch= doc.getChar(pos1))) { pos1++; } if (pos1 < end) { // for method references, search the closing bracket if ((ch == '(') && newText.endsWith(")")) { //$NON-NLS-1$ return findClosingCharacter(doc, pos1, end, ')'); } } return pos1; } } catch (BadLocationException e) { e.printStackTrace(); } return pos; } public ICompletionProposal[] computeProposals() throws JavaModelException { evalProposals(); ICompletionProposal[] res= new ICompletionProposal[fResult.size()]; fResult.toArray(res); fResult.clear(); return res; } private void evalProposals() throws JavaModelException { try { IRegion info= fDocument.getLineInformationOfOffset(fCurrentPos); int lineBeginPos= info.getOffset(); int word1Begin= findCharBeforeWord(fDocument, lineBeginPos, fCurrentPos); if (word1Begin == fCurrentPos) { return; } char firstChar= fDocument.getChar(word1Begin); if (firstChar == '@') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgTagProposals, JavaPluginImages.IMG_OBJS_JAVADOCTAG); return; } else if (firstChar == '<') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgHTMLProposals, JavaPluginImages.IMG_OBJS_HTMLTAG); return; } else if (!Character.isWhitespace(firstChar)) { return; } String prefix= fDocument.get(word1Begin + 1, fCurrentPos - word1Begin - 1); // could be a composed java doc construct (@param, @see ...) int word2End= findLastWhitespace(fDocument, lineBeginPos, word1Begin); if (word2End != lineBeginPos) { // find the word before the prefix int word2Begin= findCharBeforeWord(fDocument, lineBeginPos, word2End); if (fDocument.getChar(word2Begin) == '@') { String tag= fDocument.get(word2Begin, word2End - word2Begin); if (addArgumentProposals(tag, prefix)) { return; } } } addAllTags(prefix); } catch (BadLocationException e) { // ignore } } private boolean prefixMatches(String prefix, String proposal) { if (fRestrictToMatchingCase) { return proposal.startsWith(prefix); } else if (proposal.length() >= prefix.length()) { return prefix.equalsIgnoreCase(proposal.substring(0, prefix.length())); } return false; } private void addAllTags(String prefix) { String jdocPrefix= "@" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgTagProposals.length; i++) { String curr= fgTagProposals[i]; if (prefixMatches(jdocPrefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG), null)); } } String htmlPrefix= "<" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgHTMLProposals.length; i++) { String curr= fgHTMLProposals[i]; if (prefixMatches(htmlPrefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_HTMLTAG), null)); } } } private void addProposals(String prefix, String[] choices, String imageName) { for (int i= 0; i < choices.length; i++) { String curr= choices[i]; if (prefixMatches(prefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(imageName), null)); } } } private void addProposals(String prefix, IJavaElement[] choices) { for (int i= 0; i < choices.length; i++) { IJavaElement elem= choices[i]; String curr= getReplaceString(elem); if (prefixMatches(prefix, curr)) { String info= getProposalInfo(elem); fResult.add(createCompletion(curr, prefix, fLabelProvider.getText(elem), fLabelProvider.getImage(elem), info)); } } } private String getProposalInfo(IJavaElement elem) { if (elem instanceof IMember) { try { Reader reader= JavaDocAccess.getJavaDoc((IMember)elem); if (reader != null) { return (new JavaDoc2HTMLTextReader(reader)).getString(); } } catch (JavaModelException e) { JavaPlugin.getDefault().log(e); } catch (IOException e) { JavaPlugin.getDefault().log(e); } } return null; } private String getReplaceString(IJavaElement elem) { if (elem instanceof IMethod) { IMethod meth= (IMethod)elem; StringBuffer buf= new StringBuffer(); buf.append(meth.getElementName()); buf.append('('); String[] types= meth.getParameterTypes(); int last= types.length - 1; for (int i= 0; i <= last; i++) { buf.append(Signature.toString(types[i])); if (i != last) { buf.append(", "); //$NON-NLS-1$ } } buf.append(')'); return buf.toString(); } else { return elem.getElementName(); } } /** * Returns true if case is handeled */ private boolean addArgumentProposals(String tag, String argument) throws JavaModelException { if ("@see".equals(tag) || "@link".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$ evalSeeTag(argument); return true; } else if ("@param".equals(tag)) { //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IMethod) { String[] names= ((IMethod)elem).getParameterNames(); addProposals(argument, names, JavaPluginImages.IMG_MISC_DEFAULT); } return true; } else if ("@throws".equals(tag) || "@exception".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IMethod) { String[] exceptions= ((IMethod)elem).getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { String curr= Signature.toString(exceptions[i]); if (prefixMatches(argument, curr)) { fResult.add(createCompletion(curr, argument, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS), null)); } } } return true; } else if ("@serialData".equals(tag)) { //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IField) { String name= ((IField)elem).getElementName(); fResult.add(createCompletion(name, argument, name, fLabelProvider.getImage(elem), null)); } return true; } return false; } private void evalSeeTag(String arg) throws JavaModelException { int wordStart= fCurrentPos - arg.length(); int pidx= arg.indexOf('#'); if (pidx == -1) { ICompletionProposal[] completions= getTypeNameCompletion(wordStart); if (completions != null) { for (int i= 0; i < completions.length; i++) { fResult.add(completions[i]); } } } else { IType parent= null; if (pidx > 0) { // method or field parent= getTypeNameResolve(wordStart, wordStart + pidx); } else { // '@see #foo' IJavaElement elem= fCompilationUnit.getElementAt(wordStart); if (elem != null) { parent= (IType)JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); } } if (parent != null) { int nidx= arg.indexOf('(', pidx); if (nidx == -1) { nidx= arg.length(); } String prefix= arg.substring(pidx + 1, nidx); addProposals(prefix, parent.getMethods()); addProposals(prefix, parent.getFields()); } } } private ICompletionProposal[] getTypeNameCompletion(int wordStart) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(wordStart, fCurrentPos); if (preparedCU != null) { ResultCollector collector= new ResultCollector(); collector.reset(fCurrentPos, fCompilationUnit.getJavaProject(), fCompilationUnit); try { preparedCU.codeComplete(fCurrentPos, collector); } finally { preparedCU.destroy(); } return collector.getResults(); } return null; } private IType getTypeNameResolve(int wordStart, int wordEnd) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(wordStart, wordEnd); if (preparedCU != null) { try { IJavaElement[] elements= preparedCU.codeSelect(wordStart, wordEnd - wordStart); if (elements != null && elements.length == 1 && elements[0] instanceof IType) { return (IType) elements[0]; } } finally { preparedCU.getBuffer().setContents(fCompilationUnit.getBuffer().getCharacters()); preparedCU.destroy(); } } return null; } private ICompilationUnit createPreparedCU(int wordStart, int wordEnd) throws JavaModelException { IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (!(elem instanceof ISourceReference)) { return null; } int startpos= ((ISourceReference)elem).getSourceRange().getOffset(); // 1GEYJ5Z: ITPJUI:WINNT - smoke120: code assist in @see tag can result data loss char[] content= (char[]) fCompilationUnit.getBuffer().getCharacters().clone(); if (wordStart < content.length) { for (int i= startpos; i < wordStart; i++) { content[i]= ' '; } } if (wordEnd + 2 < content.length) { // XXX: workaround for 1GAVL08 content[wordEnd]= ' '; content[wordEnd + 1]= 'x'; } ICompilationUnit cu= fCompilationUnit; if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } ICompilationUnit newCU= (ICompilationUnit) cu.getWorkingCopy(); newCU.getBuffer().setContents(content); return newCU; } private ICompletionProposal createCompletion(String newText, String oldText, String labelText, Image image, String info) { int offset= fCurrentPos - oldText.length(); int length= fCurrentLength + oldText.length(); if (fCurrentLength == 0) length= findReplaceEndPos(fDocument, newText, oldText, fCurrentPos) - offset; return new CompletionProposal(newText, offset, length, newText.length(), image, labelText, null, info); } }
12,087
Bug 12087 problem while closing the project
i am using eclipse 20020314 build. i have 5 projects on my workspace with all but one closed. when i am closing this one with some files open in editor, it is giving error messages in message box saying project 1 not open, project 2 not open .... log says Log: Thu Mar 21 11:54:00 IST 2002 4 org.eclipse.core.resources 372 Resource /cxindeploy is not open. Log: Thu Mar 21 11:54:01 IST 2002 4 org.eclipse.core.resources 372 Resource /cxindeploy is not open. Log: Thu Mar 21 11:54:01 IST 2002 4 org.eclipse.core.resources 372 Resource /jdt is not open. Log: Thu Mar 21 11:54:01 IST 2002 4 org.eclipse.core.resources 372 Resource /jdtcore is not open. Log: Thu Mar 21 11:54:01 IST 2002 4 org.eclipse.core.resources 372 Resource /mycxpita is not open. Log: Thu Mar 21 11:54:01 IST 2002 4 org.eclipse.core.resources 372 Resource /test is not open. Log: Thu Mar 21 11:54:01 IST 2002 ne help ?? thanx in advance Nachiketa Sahoo
resolved fixed
7243c80
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T16:17:37Z
2002-03-22T06:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ProblemMarkerManager.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.viewsupport; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IMarkerDelta; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.util.ListenerList; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Listens to resource deltas and filters for marker changes of type IMarker.PROBLEM * Viewers showing error ticks should register as listener to * this type. */ public class ProblemMarkerManager implements IResourceChangeListener { /** * Visitors used to filter the element delta changes */ private static class ProjectErrorVisitor implements IResourceDeltaVisitor { private HashSet fChangedElements; public ProjectErrorVisitor(HashSet changedElements) { fChangedElements= changedElements; } public boolean visit(IResourceDelta delta) throws CoreException { IResource res= delta.getResource(); if (res instanceof IProject && delta.getKind() == IResourceDelta.CHANGED) { try { IProject project= (IProject) res; if (!(project.hasNature(JavaCore.NATURE_ID) && project.isOpen())) { // only track open Java projects return false; } } catch (CoreException e) { JavaPlugin.log(e.getStatus()); return false; } } checkInvalidate(delta, res.getFullPath()); return true; } private void checkInvalidate(IResourceDelta delta, IPath path) { int kind= delta.getKind(); if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) { // invalidate the path and all parent paths while (!path.isEmpty() && !path.isRoot() && !fChangedElements.contains(path)) { fChangedElements.add(path); path= path.removeLastSegments(1); } } } private boolean isErrorDelta(IResourceDelta delta) { if ((delta.getFlags() & IResourceDelta.MARKERS) != 0) { IMarkerDelta[] markerDeltas= delta.getMarkerDeltas(); for (int i= 0; i < markerDeltas.length; i++) { if (markerDeltas[i].isSubtypeOf(IMarker.PROBLEM)) { int kind= markerDeltas[i].getKind(); if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) return true; int severity= markerDeltas[i].getAttribute(IMarker.SEVERITY, -1); int newSeverity= markerDeltas[i].getMarker().getAttribute(IMarker.SEVERITY, -1); if (newSeverity != severity) return true; } } } return false; } } private ListenerList fListeners; public ProblemMarkerManager() { fListeners= new ListenerList(5); } /* * @see IResourceChangeListener#resourceChanged */ public void resourceChanged(IResourceChangeEvent event) { HashSet changedElements= new HashSet(); try { IResourceDelta delta= event.getDelta(); if (delta != null) delta.accept(new ProjectErrorVisitor(changedElements)); } catch (CoreException e) { JavaPlugin.log(e.getStatus()); } if (changedElements.size() > 0) { fireChanges(changedElements); } } /** * Adds a listener for problem marker changes. */ public void addListener(IProblemChangedListener listener) { if (fListeners.isEmpty()) { JavaPlugin.getWorkspace().addResourceChangeListener(this); } fListeners.add(listener); } /** * Removes a <code>IProblemChangedListener</code>. */ public void removeListener(IProblemChangedListener listener) { fListeners.remove(listener); if (fListeners.isEmpty()) { JavaPlugin.getWorkspace().removeResourceChangeListener(this); } } private void fireChanges(Set changes) { Object[] listeners= fListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { IProblemChangedListener curr= (IProblemChangedListener) listeners[i]; curr.problemsChanged(changes); } } }
3,975
Bug 3975 New Class Wizard does not detect package if a resource is selected (1GFCU9G)
1. JUnit setup 2. Select ok.gif in junit.swingui 3. Open New Class wizard ==> package is default instead of junit.swingui (as if a class would have been selected) NOTES:
resolved fixed
86be48a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T16:41:45Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewContainerWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.ui.wizards; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.*; import org.eclipse.jdt.ui.JavaElementContentProvider; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; /** * Base class for Java wizards. Provides source folder selection UI, validation and creation. * @since 2.0 */ public abstract class NewContainerWizardPage extends NewElementWizardPage { /** * container field id */ protected static final String CONTAINER= "NewContainerWizardPage.container"; //$NON-NLS-1$ /** * Status of last validation */ protected IStatus fContainerStatus; private StringButtonDialogField fContainerDialogField; /* * package fragment root corresponding to the input type (can be null) */ private IPackageFragmentRoot fCurrRoot; private IWorkspaceRoot fWorkspaceRoot; public NewContainerWizardPage(String name) { super(name); fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); ContainerFieldAdapter adapter= new ContainerFieldAdapter(); fContainerDialogField= new StringButtonDialogField(adapter); fContainerDialogField.setDialogFieldListener(adapter); fContainerDialogField.setLabelText(NewWizardMessages.getString("NewContainerWizardPage.container.label")); //$NON-NLS-1$ fContainerDialogField.setButtonLabel(NewWizardMessages.getString("NewContainerWizardPage.container.button")); //$NON-NLS-1$ fContainerStatus= new StatusInfo(); fCurrRoot= null; } /** * Initializes the fields provided by the container page with a given * Java element as selection. * @param elem The initial selection of this page or null if no * selection was available */ protected void initContainerPage(IJavaElement elem) { IPackageFragmentRoot initRoot= null; if (elem != null) { initRoot= JavaModelUtil.getPackageFragmentRoot(elem); if (initRoot == null || initRoot.isArchive()) { IJavaProject jproject= elem.getJavaProject(); try { initRoot= null; IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { initRoot= roots[i]; break; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } if (initRoot == null) { initRoot= jproject.getPackageFragmentRoot(""); //$NON-NLS-1$ } } } setPackageFragmentRoot(initRoot, true); } /** * Utility method to inspect a selection to find a Java element as initial element. * @return Returns a Java element to use as initial selection, or <code>null</code>, * if none is found. */ protected IJavaElement getInitialJavaElement(IStructuredSelection selection) { IJavaElement jelem= null; if (selection != null && !selection.isEmpty()) { Object selectedElement= selection.getFirstElement(); if (selectedElement instanceof IAdaptable) { IAdaptable adaptable= (IAdaptable) selectedElement; jelem= (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (jelem == null) { IResource resource= (IResource) adaptable.getAdapter(IResource.class); if (resource != null) { IProject proj= resource.getProject(); if (proj != null) { jelem= JavaCore.create(proj); } } } } } if (jelem == null) { jelem= EditorUtility.getActiveEditorJavaInput(); } if (jelem == null) { IProject[] projects= getWorkspaceRoot().getProjects(); if (projects.length > 0) { jelem= JavaCore.create(projects[0]); } } return jelem; } /** * Returns the recommended maximum width for text fields (in pixels) * Not valid until entering createContent. * Overwrite to change value. */ protected int getMaxFieldWidth() { return convertWidthInCharsToPixels(40); } /** * Creates the controls for the container field. Expects a GridLayout with at least 3 columns. * @param parent The parent composite * @param nColumns The number of columns to span */ protected void createContainerControls(Composite parent, int nColumns) { fContainerDialogField.doFillIntoGrid(parent, nColumns); LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), getMaxFieldWidth()); } protected void setFocusOnContainer() { fContainerDialogField.setFocus(); } // -------- ContainerFieldAdapter -------- private class ContainerFieldAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { containerChangeControlPressed(field); } // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { containerDialogFieldChanged(field); } } private void containerChangeControlPressed(DialogField field) { // take the current jproject as init element of the dialog IPackageFragmentRoot root= getPackageFragmentRoot(); root= chooseSourceContainer(root); if (root != null) { setPackageFragmentRoot(root, true); } } private void containerDialogFieldChanged(DialogField field) { if (field == fContainerDialogField) { fContainerStatus= containerChanged(); } // tell all others handleFieldChanged(CONTAINER); } // ----------- validation ---------- /** * Called after the container field has changed. * Updates the model and returns the status. * Model is only valid if returned status is OK */ protected IStatus containerChanged() { StatusInfo status= new StatusInfo(); fCurrRoot= null; String str= getPackageFragmentRootText(); if (str.length() == 0) { status.setError(NewWizardMessages.getString("NewContainerWizardPage.error.EnterContainerName")); //$NON-NLS-1$ return status; } IPath path= new Path(str); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { int resType= res.getType(); if (resType == IResource.PROJECT || resType == IResource.FOLDER) { IProject proj= res.getProject(); if (!proj.isOpen()) { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$ return status; } IJavaProject jproject= JavaCore.create(proj); fCurrRoot= jproject.getPackageFragmentRoot(res); if (fCurrRoot.exists()) { try { if (!proj.hasNature(JavaCore.NATURE_ID)) { if (resType == IResource.PROJECT) { status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$ } else { status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotInAJavaProject")); //$NON-NLS-1$ } return status; } } catch (CoreException e) { status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$ } try { if (!JavaModelUtil.isOnBuildPath(jproject, fCurrRoot)) { status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", str)); //$NON-NLS-1$ } } catch (JavaModelException e) { status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", str)); //$NON-NLS-1$ } if (fCurrRoot.isArchive()) { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerIsBinary", str)); //$NON-NLS-1$ return status; } } return status; } else { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.NotAFolder", str)); //$NON-NLS-1$ return status; } } else { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$ return status; } } // -------- update message ---------------- /** * Called when a field on a page changed. Every sub type is responsible to * call this method when a field on its page has changed. * Subtypes override (extend) the method to add verification when own field has a * dependency to an other field. (for example the class name input must be verified * again, when the package field changes (check for duplicated class names)) * @param fieldName The name of the field that has changed (field id) */ protected void handleFieldChanged(String fieldName) { } // ---- get ---------------- /** * Returns the workspace root. */ protected IWorkspaceRoot getWorkspaceRoot() { return fWorkspaceRoot; } /** * Returns the PackageFragmentRoot corresponding to the current input. * @return the PackageFragmentRoot or <code>null</code> if the current * input is not a valid source folder */ public IPackageFragmentRoot getPackageFragmentRoot() { return fCurrRoot; } /** * Returns the text of the container field. */ public String getPackageFragmentRootText() { return fContainerDialogField.getText(); } /** * Sets the current PackageFragmentRoot (model and text field). * @param canBeModified Selects if the container field can be changed by the user */ public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean canBeModified) { fCurrRoot= root; String str= (root == null) ? "" : root.getPath().makeRelative().toString(); //$NON-NLS-1$ fContainerDialogField.setText(str); fContainerDialogField.setEnabled(canBeModified); } // ------------- choose source container dialog private IPackageFragmentRoot chooseSourceContainer(IJavaElement initElement) { Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) { public boolean isSelectedValid(Object element) { try { if (element instanceof IJavaProject) { IJavaProject jproject= (IJavaProject)element; IPath path= jproject.getProject().getFullPath(); return (jproject.findPackageFragmentRoot(path) != null); } else if (element instanceof IPackageFragmentRoot) { return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); } return true; } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // just log, no ui in validation } return false; } }; acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IPackageFragmentRoot) { try { return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // just log, no ui in validation return false; } } return super.select(viewer, parent, element); } }; JavaElementContentProvider provider= new JavaElementContentProvider(); ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider); dialog.setValidator(validator); dialog.setSorter(new JavaElementSorter()); dialog.setTitle(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(JavaCore.create(fWorkspaceRoot)); dialog.setInitialSelection(initElement); if (dialog.open() == dialog.OK) { Object element= dialog.getFirstResult(); if (element instanceof IJavaProject) { IJavaProject jproject= (IJavaProject)element; return jproject.getPackageFragmentRoot(jproject.getProject()); } else if (element instanceof IPackageFragmentRoot) { return (IPackageFragmentRoot)element; } return null; } return null; } }
3,992
Bug 3992 DCR: Need a "merged package" filter on Packages view (1GFKR0A)
This is for future, but would be really really nice. (it has probably been reported before by someone from the SWT team because our setup makes the need for this feature so obvious). Please add a filter to the Packages view that reorganizes the view so that PACKAGES are at the top level instead of FOLDERS. The current organization of the packages view spreads our SWT packages out over all of the folders that they are in, and it makes it hard to see all of the SWT packages. A much more useful view would be to have everything grouped into their containing package. For example, we have had to split the SWT packages across platform lines, and we therefore have folders for 'common', 'win32', 'motif', etc. When the .classpath is specified for Windows, only 'common' and 'win32' folders are displayed (with the cute little folder icon with a package peeking out of them). So we end up with 2 'folders' for each package. This looks like: Eclipse SWT/common Eclipse SWT/win32 Eclipse SWT Printing/common Eclipse SWT Printing/win32 Eclipse SWT Program/common Eclipse SWT Program/win32 Eclipse SWT Drag and Drop/common Eclipse SWT Drag and Drop/win32 So in order to find, say, the widgets package, you have to expand BOTH Eclipse SWT/common and Eclipse SWT/win32 folders, and you are constantly having to switch back and forth between the folders to see all of the classes in the package. This is sub-optimal. The optimal packages view would merge the folders by package, so we would only have to go to the package and expand one thing. Of course, it needs to be optional, because there are (rare) times when you do care what folder something is in (such as when you are organizing the folders in the first place). NOTES: VI (6/19/2001 4:43:32 PM) For an example of what it should look like, see the "bin" folder. CM (6/19/2001 4:43:53 PM) But make sure that the .class files from "bin" are not also showing in the packages. SN (6/19/2001 4:44:40 PM) If this filter is on, then search, open type, etc., etc., should only find what is on your classpath. (i.e. currently when we say "Open Type" we have to select the type for win32, motif, gtk, photon, ...) A whole new view that showed only packages and their classes (in their hierarchies!) would make me very happy.
resolved fixed
ef84cc3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:04:15Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HierarchyAdornmentProvider.java
package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IJavaElement; 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.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.AppearancePreferencePage; import org.eclipse.jdt.internal.ui.viewsupport.IAdornmentProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; public class HierarchyAdornmentProvider implements IAdornmentProvider { private TypeHierarchyLifeCycle fHierarchy; /** * Constructor for HierarchyLabelProvider. * @param flags */ public HierarchyAdornmentProvider(TypeHierarchyLifeCycle hierarchy) { super(); fHierarchy= hierarchy; } /* * @see IAdornmentProvider#computeAdornmentFlags(Object) */ public int computeAdornmentFlags(Object element) { if (element instanceof IType) { IType type= (IType) element; IJavaElement input= fHierarchy.getInputElement(); if (input != null && input.getElementType() != IJavaElement.TYPE) { IJavaElement parent= JavaModelUtil.findElementOfKind(type, input.getElementType()); if (!input.equals(parent)) { return JavaElementImageProvider.LIGHT_TYPE_ICONS; } } } else if (element instanceof IMethod && AppearancePreferencePage.showOverrideIndicators()) { try { IMethod method= (IMethod) element; int flags= method.getFlags(); IType type= method.getDeclaringType(); ITypeHierarchy hierarchy= fHierarchy.getHierarchy(); if (type.isClass() && !method.isConstructor() && !Flags.isPrivate(flags) && !Flags.isStatic(flags) && (hierarchy != null)) { IMethod impl= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, method.getElementName(), method.getParameterTypes(), false); if (impl != null) { IMethod overridden= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, method.getElementName(), method.getParameterTypes(), false); if (overridden != null) { return JavaElementImageProvider.OVERLAY_OVERRIDE; } else { return JavaElementImageProvider.OVERLAY_IMPLEMENTS; } } } } catch (JavaModelException e) { JavaPlugin.log(e); } } return 0; } /* * @see IAdornmentProvider#dispose */ public void dispose() { } }
3,992
Bug 3992 DCR: Need a "merged package" filter on Packages view (1GFKR0A)
This is for future, but would be really really nice. (it has probably been reported before by someone from the SWT team because our setup makes the need for this feature so obvious). Please add a filter to the Packages view that reorganizes the view so that PACKAGES are at the top level instead of FOLDERS. The current organization of the packages view spreads our SWT packages out over all of the folders that they are in, and it makes it hard to see all of the SWT packages. A much more useful view would be to have everything grouped into their containing package. For example, we have had to split the SWT packages across platform lines, and we therefore have folders for 'common', 'win32', 'motif', etc. When the .classpath is specified for Windows, only 'common' and 'win32' folders are displayed (with the cute little folder icon with a package peeking out of them). So we end up with 2 'folders' for each package. This looks like: Eclipse SWT/common Eclipse SWT/win32 Eclipse SWT Printing/common Eclipse SWT Printing/win32 Eclipse SWT Program/common Eclipse SWT Program/win32 Eclipse SWT Drag and Drop/common Eclipse SWT Drag and Drop/win32 So in order to find, say, the widgets package, you have to expand BOTH Eclipse SWT/common and Eclipse SWT/win32 folders, and you are constantly having to switch back and forth between the folders to see all of the classes in the package. This is sub-optimal. The optimal packages view would merge the folders by package, so we would only have to go to the package and expand one thing. Of course, it needs to be optional, because there are (rare) times when you do care what folder something is in (such as when you are organizing the folders in the first place). NOTES: VI (6/19/2001 4:43:32 PM) For an example of what it should look like, see the "bin" folder. CM (6/19/2001 4:43:53 PM) But make sure that the .class files from "bin" are not also showing in the packages. SN (6/19/2001 4:44:40 PM) If this filter is on, then search, open type, etc., etc., should only find what is on your classpath. (i.e. currently when we say "Open Type" we have to select the type for win32, motif, gtk, photon, ...) A whole new view that showed only packages and their classes (in their hierarchies!) would make me very happy.
resolved fixed
ef84cc3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:04:15Z
2001-10-11T03:13:20Z
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.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.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.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; /** * 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 List fChangeListeners; public TypeHierarchyLifeCycle() { this(false); } public TypeHierarchyLifeCycle(boolean isSuperTypesOnly) { fHierarchy= null; fInputElement= null; fIsSuperTypesOnly= isSuperTypesOnly; fChangeListeners= new ArrayList(2); } 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) 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); } } }; try { new BusyIndicatorRunnableContext().run(false, false, 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 { 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 (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: if (delta.getKind() == IJavaElementDelta.CHANGED && isPossibleStructuralChange(delta.getFlags())) { try { IType[] types= ((ICompilationUnit) element).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 void processTypeDelta(IType type, ArrayList changedTypes) { 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 } } }
4,166
Bug 4166 DCR: Javadoc for implementers of a method (1GJJ5LD)
If I hover over a method which implements an interface or overrides a method I would like to see the corresponding Javadoc (unless I also added my own Javadoc). NOTES:
resolved fixed
21b8181
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:38:40Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/core
4,166
Bug 4166 DCR: Javadoc for implementers of a method (1GJJ5LD)
If I hover over a method which implements an interface or overrides a method I would like to see the corresponding Javadoc (unless I also added my own Javadoc). NOTES:
resolved fixed
21b8181
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:38:40Z
2001-10-11T03:13:20Z
extension/org/eclipse/jdt/internal/corext/javadoc/JavaDocAccess.java
4,166
Bug 4166 DCR: Javadoc for implementers of a method (1GJJ5LD)
If I hover over a method which implements an interface or overrides a method I would like to see the corresponding Javadoc (unless I also added my own Javadoc). NOTES:
resolved fixed
21b8181
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:38:40Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ProposalInfo.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.io.IOException; import java.io.Reader; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader; public class ProposalInfo { private static final int NUMBER_OF_JAVADOC_LINES= 12; private IJavaProject fJavaProject; private char[] fPackageName; private char[] fTypeName; private char[] fMemberName; private char[][] fParameterPackages; private char[][] fParameterTypes; private boolean fIsConstructor; public ProposalInfo(IJavaProject jproject, char[] packName, char[] typeQualifiedName, char[] methodName, char[][] paramPackages, char[][] paramTypes, boolean isConstructor) { fJavaProject= jproject; fPackageName= packName; fTypeName= typeQualifiedName; fMemberName= methodName; fParameterPackages= paramPackages; fParameterTypes= paramTypes; fIsConstructor= isConstructor; } public ProposalInfo(IJavaProject jproject, char[] packName, char[] typeQualifiedName) { this(jproject, packName, typeQualifiedName, null, null, null, false); } public ProposalInfo(IJavaProject jproject, char[] packName, char[] typeQualifiedName, char[] fieldName) { this(jproject, packName, typeQualifiedName, fieldName, null, null, false); } private String getParameterSignature(int index) { StringBuffer buf= new StringBuffer(); char[] pack= fParameterPackages[index]; if (pack != null && pack.length > 0) { buf.append(pack); buf.append('.'); } buf.append(fParameterTypes[index]); return Signature.createTypeSignature(buf.toString(), true); } /** * Gets the text for this proposal info */ public String getInfo() { try { IType type= JavaModelUtil.findType(fJavaProject, new String(fPackageName), new String(fTypeName)); if (type != null) { IMember member= null; if (fMemberName != null) { String name= new String(fMemberName); if (fParameterTypes != null) { String[] paramTypes= new String[fParameterTypes.length]; for (int i= 0; i < fParameterTypes.length; i++) { paramTypes[i]= getParameterSignature(i); } member= JavaModelUtil.findMethod(name, paramTypes, fIsConstructor, type); } else { IField field= type.getField(name); if (field.exists()) { member= field; } } } else { member= type; } if (member != null) { Reader reader= JavaDocAccess.getJavaDoc(member); if (reader != null) { return new JavaDoc2HTMLTextReader(reader).getString(); } } } } catch (JavaModelException e) { JavaPlugin.log(e); } catch (IOException e) { JavaPlugin.log(e); } return null; } }
4,166
Bug 4166 DCR: Javadoc for implementers of a method (1GJJ5LD)
If I hover over a method which implements an interface or overrides a method I would like to see the corresponding Javadoc (unless I also added my own Javadoc). NOTES:
resolved fixed
21b8181
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:38:40Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaTypeHover.java
package org.eclipse.jdt.internal.ui.text.java.hover; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.io.Reader; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover; import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.text.HTMLPrinter; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; public class JavaTypeHover implements IJavaEditorTextHover { private IEditorPart fEditor; private IJavaEditorTextHover fProblemHover; private final int LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED | JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS | JavaElementLabels.F_PRE_TYPE_SIGNATURE; public JavaTypeHover() { fProblemHover= new JavaProblemHover(); } /** * @see IJavaEditorTextHover#setEditor(IEditorPart) */ public void setEditor(IEditorPart editor) { fEditor= editor; fProblemHover.setEditor(editor); } private ICodeAssist getCodeAssist() { if (fEditor != null) { IEditorInput input= fEditor.getEditorInput(); if (input instanceof IClassFileEditorInput) { IClassFileEditorInput cfeInput= (IClassFileEditorInput) input; return cfeInput.getClassFile(); } IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(input); } return null; } private String getInfoText(IMember member) { return JavaElementLabels.getElementLabel(member, LABEL_FLAGS); } /* * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { String hoverInfo= fProblemHover.getHoverInfo(textViewer, hoverRegion); if (hoverInfo != null) return hoverInfo; ICodeAssist resolve= getCodeAssist(); if (resolve != null) { try { IJavaElement[] result= resolve.codeSelect(hoverRegion.getOffset(), hoverRegion.getLength()); if (result == null) return null; int nResults= result.length; if (nResults == 0) return null; StringBuffer buffer= new StringBuffer(); if (nResults > 1) { for (int i= 0; i < result.length; i++) { HTMLPrinter.startBulletList(buffer); IJavaElement curr= result[i]; if (curr instanceof IMember) HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr)); HTMLPrinter.endBulletList(buffer); } } else { IJavaElement curr= result[0]; if (curr instanceof IMember) { IMember member= (IMember) curr; HTMLPrinter.addSmallHeader(buffer, getInfoText(member)); Reader reader= JavaDocAccess.getJavaDoc(member); if (reader != null) { HTMLPrinter.addParagraph(buffer, new JavaDoc2HTMLTextReader(reader)); } } } if (buffer.length() > 0) { HTMLPrinter.insertPageProlog(buffer, 0); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); } } return null; } }
4,166
Bug 4166 DCR: Javadoc for implementers of a method (1GJJ5LD)
If I hover over a method which implements an interface or overrides a method I would like to see the corresponding Javadoc (unless I also added my own Javadoc). NOTES:
resolved fixed
21b8181
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:38:40Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/CompletionEvaluator.java
package org.eclipse.jdt.internal.ui.text.javadoc; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jdt.core.CompletionRequestorAdapter; 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.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal; import org.eclipse.jdt.internal.ui.text.java.ProposalInfo; public class CompletionEvaluator { protected final static String[] fgTagProposals= { "@author", //$NON-NLS-1$ "@deprecated", //$NON-NLS-1$ "@exception", //$NON-NLS-1$ "@link", //$NON-NLS-1$ "@param", //$NON-NLS-1$ "@return", //$NON-NLS-1$ "@see", "@serial", "@serialData", "@serialField", "@since", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "@throws", //$NON-NLS-1$ "@version" //$NON-NLS-1$ }; protected final static String[] fgHTMLProposals= { "<code>", "</code>", //$NON-NLS-2$ //$NON-NLS-1$ "<br>", //$NON-NLS-1$ "<b>", "</b>", //$NON-NLS-2$ //$NON-NLS-1$ "<i>", "</i>", //$NON-NLS-2$ //$NON-NLS-1$ "<pre>", "</pre>" //$NON-NLS-2$ //$NON-NLS-1$ }; private ICompilationUnit fCompilationUnit; private IDocument fDocument; private int fCurrentPos; private int fCurrentLength; private JavaElementLabelProvider fLabelProvider; private List fResult; private boolean fRestrictToMatchingCase; public CompletionEvaluator(ICompilationUnit cu, IDocument doc, int pos, int length) { fCompilationUnit= cu; fDocument= doc; fCurrentPos= pos; fCurrentLength= length; fResult= new ArrayList(); fRestrictToMatchingCase= false; fLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_POST_QUALIFIED | JavaElementLabelProvider.SHOW_PARAMETERS); } /** * Tells this evaluator to restrict is proposals to those * starting with matching cases. * * @param restrict <code>true</code> if proposals should be restricted */ public void restrictProposalsToMatchingCases(boolean restrict) { fRestrictToMatchingCase= restrict; } private static boolean isWordPart(char ch) { return Character.isJavaIdentifierPart(ch) || (ch == '#') || (ch == '.') || (ch == '/'); } private static int findCharBeforeWord(IDocument doc, int lineBeginPos, int pos) { int currPos= pos - 1; if (currPos > lineBeginPos) { try { while (currPos > lineBeginPos && isWordPart(doc.getChar(currPos))) { currPos--; } return currPos; } catch (BadLocationException e) { } } return pos; } private static int findLastWhitespace(IDocument doc, int lineBeginPos, int pos) { try { int currPos= pos - 1; while (currPos >= lineBeginPos && Character.isWhitespace(doc.getChar(currPos))) { currPos--; } return currPos + 1; } catch (BadLocationException e) { } return pos; } private static int findClosingCharacter(IDocument doc, int pos, int end, char endChar) throws BadLocationException { int curr= pos; while (curr < end && (doc.getChar(curr) != endChar)) { curr++; } if (curr < end) { return curr + 1; } return pos; } private static int findReplaceEndPos(IDocument doc, String newText, String oldText, int pos) { if (oldText.length() == 0 || oldText.equals(newText)) { return pos; } try { IRegion lineInfo= doc.getLineInformationOfOffset(pos); int end= lineInfo.getOffset() + lineInfo.getLength(); if (newText.endsWith(">")) { //$NON-NLS-1$ // for html, search the tag end character return findClosingCharacter(doc, pos, end, '>'); } else { char ch= 0; int pos1= pos; while (pos1 < end && Character.isJavaIdentifierPart(ch= doc.getChar(pos1))) { pos1++; } if (pos1 < end) { // for method references, search the closing bracket if ((ch == '(') && newText.endsWith(")")) { //$NON-NLS-1$ return findClosingCharacter(doc, pos1, end, ')'); } } return pos1; } } catch (BadLocationException e) { e.printStackTrace(); } return pos; } public ICompletionProposal[] computeProposals() throws JavaModelException { evalProposals(); ICompletionProposal[] res= new ICompletionProposal[fResult.size()]; fResult.toArray(res); fResult.clear(); return res; } private void evalProposals() throws JavaModelException { try { IRegion info= fDocument.getLineInformationOfOffset(fCurrentPos); int lineBeginPos= info.getOffset(); int word1Begin= findCharBeforeWord(fDocument, lineBeginPos, fCurrentPos); if (word1Begin == fCurrentPos) { return; } char firstChar= fDocument.getChar(word1Begin); if (firstChar == '@') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgTagProposals, JavaPluginImages.IMG_OBJS_JAVADOCTAG); return; } else if (firstChar == '<') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgHTMLProposals, JavaPluginImages.IMG_OBJS_HTMLTAG); return; } else if (!Character.isWhitespace(firstChar)) { return; } String prefix= fDocument.get(word1Begin + 1, fCurrentPos - word1Begin - 1); // could be a composed java doc construct (@param, @see ...) int word2End= findLastWhitespace(fDocument, lineBeginPos, word1Begin); if (word2End != lineBeginPos) { // find the word before the prefix int word2Begin= findCharBeforeWord(fDocument, lineBeginPos, word2End); if (fDocument.getChar(word2Begin) == '@') { String tag= fDocument.get(word2Begin, word2End - word2Begin); if (addArgumentProposals(tag, prefix)) { return; } } } addAllTags(prefix); } catch (BadLocationException e) { // ignore } } private boolean prefixMatches(String prefix, String proposal) { if (fRestrictToMatchingCase) { return proposal.startsWith(prefix); } else if (proposal.length() >= prefix.length()) { return prefix.equalsIgnoreCase(proposal.substring(0, prefix.length())); } return false; } private void addAllTags(String prefix) { String jdocPrefix= "@" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgTagProposals.length; i++) { String curr= fgTagProposals[i]; if (prefixMatches(jdocPrefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG), null)); } } String htmlPrefix= "<" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgHTMLProposals.length; i++) { String curr= fgHTMLProposals[i]; if (prefixMatches(htmlPrefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_HTMLTAG), null)); } } } private void addProposals(String prefix, String[] choices, String imageName) { for (int i= 0; i < choices.length; i++) { String curr= choices[i]; if (prefixMatches(prefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(imageName), null)); } } } private void addProposals(String prefix, IJavaElement[] choices) { for (int i= 0; i < choices.length; i++) { IJavaElement elem= choices[i]; String curr= getReplaceString(elem); if (prefixMatches(prefix, curr)) { String info= getProposalInfo(elem); fResult.add(createCompletion(curr, prefix, fLabelProvider.getText(elem), fLabelProvider.getImage(elem), info)); } } } private String getProposalInfo(IJavaElement elem) { if (elem instanceof IMember) { try { Reader reader= JavaDocAccess.getJavaDoc((IMember)elem); if (reader != null) { return (new JavaDoc2HTMLTextReader(reader)).getString(); } } catch (JavaModelException e) { JavaPlugin.log(e); } catch (IOException e) { JavaPlugin.log(e); } } return null; } private String getReplaceString(IJavaElement elem) { if (elem instanceof IMethod) { IMethod meth= (IMethod)elem; StringBuffer buf= new StringBuffer(); buf.append(meth.getElementName()); buf.append('('); String[] types= meth.getParameterTypes(); int last= types.length - 1; for (int i= 0; i <= last; i++) { buf.append(Signature.toString(types[i])); if (i != last) { buf.append(", "); //$NON-NLS-1$ } } buf.append(')'); return buf.toString(); } else { return elem.getElementName(); } } /** * Returns true if case is handeled */ private boolean addArgumentProposals(String tag, String argument) throws JavaModelException { if ("@see".equals(tag) || "@link".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$ evalSeeTag(argument); return true; } else if ("@param".equals(tag)) { //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IMethod) { String[] names= ((IMethod)elem).getParameterNames(); addProposals(argument, names, JavaPluginImages.IMG_MISC_DEFAULT); } return true; } else if ("@throws".equals(tag) || "@exception".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IMethod) { String[] exceptions= ((IMethod)elem).getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { String curr= Signature.toString(exceptions[i]); if (prefixMatches(argument, curr)) { fResult.add(createCompletion(curr, argument, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS), null)); } } } return true; } else if ("@serialData".equals(tag)) { //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IField) { String name= ((IField)elem).getElementName(); fResult.add(createCompletion(name, argument, name, fLabelProvider.getImage(elem), null)); } return true; } return false; } private void evalSeeTag(String arg) throws JavaModelException { int wordStart= fCurrentPos - arg.length(); int pidx= arg.indexOf('#'); if (pidx == -1) { evalTypeNameCompletions(wordStart); } else { IType parent= null; if (pidx > 0) { // method or field parent= getTypeNameResolve(wordStart, wordStart + pidx); } else { // '@see #foo' IJavaElement elem= fCompilationUnit.getElementAt(wordStart); if (elem != null) { parent= (IType)JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); } } if (parent != null) { int nidx= arg.indexOf('(', pidx); if (nidx == -1) { nidx= arg.length(); } String prefix= arg.substring(pidx + 1, nidx); addProposals(prefix, parent.getMethods()); addProposals(prefix, parent.getFields()); } } } private void evalTypeNameCompletions(int wordStart) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(wordStart, fCurrentPos); if (preparedCU != null) { CompletionRequestorAdapter requestor= new CompletionRequestorAdapter() { public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int start, int end) { fResult.add(createSeeTypeCompletion(true, start, end, completionName, className, packageName)); } public void acceptInterface(char[] packageName, char[] interfaceName, char[] completionName, int modifiers, int start, int end) { fResult.add(createSeeTypeCompletion(false, start, end, completionName, interfaceName, packageName)); } public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end) { fResult.add(createSeeTypeCompletion(true, start, end, completionName, typeName, packageName)); } }; try { preparedCU.codeComplete(fCurrentPos, requestor); } finally { preparedCU.destroy(); } } } private IType getTypeNameResolve(int wordStart, int wordEnd) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(wordStart, wordEnd); if (preparedCU != null) { try { IJavaElement[] elements= preparedCU.codeSelect(wordStart, wordEnd - wordStart); if (elements != null && elements.length == 1 && elements[0] instanceof IType) { return (IType) elements[0]; } } finally { preparedCU.getBuffer().setContents(fCompilationUnit.getBuffer().getCharacters()); preparedCU.destroy(); } } return null; } private ICompilationUnit createPreparedCU(int wordStart, int wordEnd) throws JavaModelException { IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (!(elem instanceof ISourceReference)) { return null; } int startpos= ((ISourceReference)elem).getSourceRange().getOffset(); char[] content= (char[]) fCompilationUnit.getBuffer().getCharacters().clone(); if (elem instanceof IType && (((IType)elem).getDeclaringType() == null) && (wordStart + 6 < content.length)) { content[startpos++]= 'i'; content[startpos++]= 'm'; content[startpos++]= 'p'; content[startpos++]= 'o'; content[startpos++]= 'r'; content[startpos++]= 't'; } if (wordStart < content.length) { for (int i= startpos; i < wordStart; i++) { content[i]= ' '; } } ICompilationUnit cu= fCompilationUnit; if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } ICompilationUnit newCU= (ICompilationUnit) cu.getWorkingCopy(); newCU.getBuffer().setContents(content); return newCU; } private ICompletionProposal createCompletion(String newText, String oldText, String labelText, Image image, String info) { int offset= fCurrentPos - oldText.length(); int length= fCurrentLength + oldText.length(); if (fCurrentLength == 0) length= findReplaceEndPos(fDocument, newText, oldText, fCurrentPos) - offset; return new CompletionProposal(newText, offset, length, newText.length(), image, labelText, null, info); } private ICompletionProposal createSeeTypeCompletion(boolean isClass, int start, int end, char[] completion, char[] typeName, char[] containerName) { ProposalInfo proposalInfo= new ProposalInfo(fCompilationUnit.getJavaProject(), containerName, typeName); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(typeName); if (containerName != null) { nameBuffer.append(" - "); //$NON-NLS-1$ if (containerName.length > 0) { nameBuffer.append(containerName); } else { nameBuffer.append(JavaDocMessages.getString("CompletionEvaluator.default_package")); } } String imageKey= isClass ? JavaPluginImages.IMG_OBJS_CLASS : JavaPluginImages.IMG_OBJS_INTERFACE; int compLen= completion.length; if (compLen > 0 && completion[compLen - 1] == ';') { compLen--; // remove the semicolon from import proposals } JavaCompletionProposal proposal= new JavaCompletionProposal(new String(completion, 0, compLen), start, end - start, JavaPluginImages.get(imageKey), nameBuffer.toString()); proposal.setProposalInfo(proposalInfo); proposal.setTriggerCharacters( new char[] { '#' }); return proposal; } }
4,166
Bug 4166 DCR: Javadoc for implementers of a method (1GJJ5LD)
If I hover over a method which implements an interface or overrides a method I would like to see the corresponding Javadoc (unless I also added my own Javadoc). NOTES:
resolved fixed
21b8181
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T17:38:40Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/JavaUIHelp.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.util; import java.io.File; import java.io.IOException; import java.net.URL; import java.text.BreakIterator; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.events.HelpEvent; import org.eclipse.swt.events.HelpListener; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.help.IContext; import org.eclipse.help.IHelp; import org.eclipse.help.IHelpResource; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.corext.javadoc.SingleCharReader; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.HTML2TextReader; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; public class JavaUIHelp { public static void setHelp(StructuredViewer viewer, String contextId) { JavaUIHelpListener listener= new JavaUIHelpListener(viewer, contextId); viewer.getControl().addHelpListener(listener); } private static class JavaUIHelpListener implements HelpListener { private StructuredViewer fViewer; private String fContextId; public JavaUIHelpListener(StructuredViewer viewer, String contextId) { fViewer= viewer; fContextId= contextId; } /* * @see HelpListener#helpRequested(HelpEvent) * */ public void helpRequested(HelpEvent e) { ISelection selection= fViewer.getSelection(); Object selected= SelectionUtil.getSingleElement(selection); IHelp help= WorkbenchHelp.getHelpSupport(); IContext context= help.getContext(fContextId); if (context == null) { return; } if (selected instanceof IJavaElement) { context= new JavaUIContext(context, (IJavaElement) selected); } WorkbenchHelp.displayHelp(context); } } private static class JavaUIContext implements IContext { private IJavaElement fElement; private IHelpResource[] fHelpResources; private IContext fContext; private String fText; public JavaUIContext(IContext context, IJavaElement element) { Assert.isNotNull(element); Assert.isNotNull(context); fElement= element; List helpResources= new ArrayList(); fContext= context; IHelpResource[] resources= context.getRelatedTopics(); if (resources != null) { for (int j= 0; j < resources.length; j++) { helpResources.add(resources[j]); } } try { URL url= JavaDocLocations.getJavaDocLocation(fElement, true); if (url == null || doesNotExist(url)) { if (fElement.getElementType() != IJavaElement.JAVA_PROJECT) { //must insure that what is sent here is lower in the hiarchy then IJavaProject IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(fElement); if (root != null) if (root.getKind() == IPackageFragmentRoot.K_BINARY) { url= JavaDocLocations.getJavaDocLocation(root, true); element= root; } else if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { url= JavaDocLocations.getJavaDocLocation(root.getJavaProject(), true); element= root.getJavaProject(); } } } if (url != null) { String extForm= url.toExternalForm(); IHelpResource javaResource= new JavaUIHelpResource(element, extForm); helpResources.add(javaResource); } } catch (CoreException e) { JavaPlugin.log(e); } fHelpResources= (IHelpResource[]) helpResources.toArray(new IHelpResource[helpResources.size()]); } private boolean doesNotExist(URL url) { if (url.getProtocol().equals("file")) { File file= new File(url.getFile()); return !file.exists(); } return false; } public IHelpResource[] getRelatedTopics() { return fHelpResources; } public String getText() { if (fElement instanceof IMember) { try { SingleCharReader reader= JavaDocAccess.getJavaDoc((IMember) fElement); if (reader != null) { HTML2TextReader htmlReader= new HTML2TextReader(reader, null); String str= htmlReader.getString(); BreakIterator breakIterator= BreakIterator.getSentenceInstance(); breakIterator.setText(str); return str.substring(0, breakIterator.next()); } else return fContext.getText(); } catch (JavaModelException e) { JavaPlugin.log(e); } catch (IOException e) { JavaPlugin.log(e); } } return fContext.getText(); } } private static class JavaUIHelpResource implements IHelpResource { private IJavaElement fElement; private String fUrl; public JavaUIHelpResource(IJavaElement element, String url) { fElement= element; fUrl= url; } public String getHref() { return fUrl; } public String getLabel() { String label= JavaElementLabels.getTextLabel(fElement, JavaElementLabels.ALL_DEFAULT); return "Javadoc for " + label; } } }
8,140
Bug 8140 Code assist for anonymous inner types adds empty line
button.addActionListener(new ActionListener() { /* * @see ActionListener#actionPerformed(ActionEvent) */ public void actionPerformed(ActionEvent e) { } <--- here ---> }
resolved fixed
2f87db2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T18:22:48Z
2002-01-23T15:33:20Z
org.eclipse.jdt.ui/core
8,140
Bug 8140 Code assist for anonymous inner types adds empty line
button.addActionListener(new ActionListener() { /* * @see ActionListener#actionPerformed(ActionEvent) */ public void actionPerformed(ActionEvent e) { } <--- here ---> }
resolved fixed
2f87db2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T18:22:48Z
2002-01-23T15:33:20Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
8,140
Bug 8140 Code assist for anonymous inner types adds empty line
button.addActionListener(new ActionListener() { /* * @see ActionListener#actionPerformed(ActionEvent) */ public void actionPerformed(ActionEvent e) { } <--- here ---> }
resolved fixed
2f87db2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T18:22:48Z
2002-01-23T15:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java
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.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.util.Assert; 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.textmanipulation.TextUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.OverrideMethodQuery; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; public class AnonymousTypeCompletionProposal extends JavaCompletionProposal { private IType fDeclaringType; private ICompilationUnit fCompilationUnit; private ImportsStructure fImportStructure; public AnonymousTypeCompletionProposal(IJavaProject jproject, ICompilationUnit cu, int start, int length, String constructorCompletion, String displayName, String declaringTypeName) { super(constructorCompletion, start, length, null, displayName); Assert.isNotNull(declaringTypeName); Assert.isNotNull(jproject); fCompilationUnit= cu; // can be null -> no imports 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 JavaModelUtil.findType(project, typeName); } catch (JavaModelException e) { JavaPlugin.log(e); } return null; } /* * @see JavaCompletionProposal#applyImports(IDocument) */ protected void applyImports(IDocument document) { if (fImportStructure != null) { try { fImportStructure.create(false, null); } catch (CoreException e) { JavaPlugin.log(e); } } } /* * @see ICompletionProposalExtension#apply(IDocument, char) */ public void apply(IDocument document, char trigger, int offset) { try { if (fCompilationUnit == null) { fImportStructure= null; } else { String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); fImportStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true); } String replacementString= getReplacementString(); // construct replacement text StringBuffer buf= new StringBuffer(); buf.append(replacementString); if (!replacementString.endsWith(")")) { buf.append(')'); } buf.append(" {\n"); if (!createStubs(buf, fImportStructure)) { return; } buf.append("}"); // use the code formatter String lineDelim= StubUtility.getLineDelimiterFor(document); int tabWidth= CodeFormatterPreferencePage.getTabSize(); IRegion region= document.getLineInformationOfOffset(getReplacementOffset()); int indent= TextUtil.getIndent(document.get(region.getOffset(), region.getLength()), tabWidth); String replacement= StubUtility.codeFormat(buf.toString(), indent, lineDelim); replacement= TextUtil.removeLeadingWhiteSpaces(replacement); setReplacementString(replacement); } catch (BadLocationException e) { JavaPlugin.log(e); } catch (CoreException e) { JavaPlugin.log(e); } super.apply(document, trigger, offset); } private boolean createStubs(StringBuffer buf, ImportsStructure imports) throws JavaModelException { if (fDeclaringType == null) { return true; } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); 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]); buf.append('\n'); } return true; } return false; } }
8,140
Bug 8140 Code assist for anonymous inner types adds empty line
button.addActionListener(new ActionListener() { /* * @see ActionListener#actionPerformed(ActionEvent) */ public void actionPerformed(ActionEvent e) { } <--- here ---> }
resolved fixed
2f87db2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T18:22:48Z
2002-01-23T15:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.compiler.env.IConstants; 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.template.Template; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /** * <code>NewTypeWizardPage</code> contains controls and validation routines for a 'New Type WizardPage' * Implementors decide which components to add and to enable. Implementors can also * customize the validation code. * <code>NewTypeWizardPage</code> is intended to serve as base class of all wizards that create types. * Applets, Servlets, Classes, Interfaces... * See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an * example usage of NewTypeWizardPage. * @since 2.0 */ public abstract class NewTypeWizardPage extends NewContainerWizardPage { private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; public NewTypeWizardPage(boolean isClass, String pageName) { super(pageName); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the type page with a given * Java element as selection. To implement a different selection strategy do not call this * method or overwrite it. * @param elem The initial selection of this page or null if no * selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= JavaModelUtil.findPrimaryType(cu); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. Expects a GridLayout with at least 1 column. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. Expects a GridLayout with at least 4 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); } /** * Creates the controls for the enclosing type name field. Expects a GridLayout with at least 4 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { // #6891 Composite tabGroup= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; tabGroup.setLayout(layout); fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= getMaxFieldWidth(); gd.horizontalSpan= 2; c.setLayoutData(gd); Button button= fEnclosingTypeDialogField.getChangeControl(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); } /** * Creates the controls for the type name field. Expects a GridLayout with at least 2 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the modifiers radio/ceckbox buttons. Expects a GridLayout with at least 3 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); Control control= fAccMdfButtons.getSelectionButtonsGroup(composite); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); control= fOtherMdfButtons.getSelectionButtonsGroup(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. Expects a GridLayout with at least 3 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the superclass name field. Expects a GridLayout with at least 3 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; gd.widthHint= getMaxFieldWidth(); } /** * Sets the focus on the type name. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /** * Called whenever a content of a field has changed. * Implementors of NewTypeWizardPage can hook in. * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Gets the text of package field. */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Gets the text of enclosing type field. */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * @return Returns <code>null</code> if the input could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the package fragment can be changed by the user */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the enclosing type corresponding to the current input. * @return Returns <code>null</code> if enclosing type is not selected or the input could not * be resolved. */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the enclosing type. * This will update model and the text of the control. * @param canBeModified Selects if the enclosing type can be changed by the user */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns <code>true</code> if the enclosing type selection check box is enabled. */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type selection checkbox. * @param canBeModified Selects if the enclosing type selection can be changed by the user */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Gets the type name. */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Gets the selected modifiers. * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= IConstants.AccPublic; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= IConstants.AccPrivate; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= IConstants.AccProtected; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= IConstants.AccAbstract; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= IConstants.AccFinal; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= IConstants.AccStatic; } return mdf; } /** * Sets the modifiers. * @param canBeModified Selects if the modifiers can be changed by the user * @see IConstants */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Gets the content of the super class text field. */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * @param canBeModified Selects if the super class can be changed by the user */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Gets the currently chosen super interfaces. * @return returns a list of String */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * @param canBeModified Selects if the modifiers can be changed by the user. * @param interfacesNames a list of String */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * Called when the package field has changed. * The method validates the package name and returns the status of the validation * This also updates the package fragment model. * Can be extended to add more validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { if (root.getJavaProject().exists() && packName.length() > 0) { try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= rootPath.append(packName.replace('.', '/')); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass } } fCurrPackage= root.getPackageFragment(packName); } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= getPackageText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Called when the enclosing type name has changed. * The method validates the enclosing type and returns the status of the validation * This also updates the enclosing type model. * Can be extended to add more validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= JavaModelUtil.findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type); if (!enclosingRoot.equals(root)) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$ } return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e); return status; } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Called when the superclass name has changed. * The method validates the superclass name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, sclassName); } } return type; } /** * Called when the list of super interface has changed. * The method validates the superinterfaces and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= JavaModelUtil.findType(root.getJavaProject(), intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, checking is an extra } } } return status; } /** * Called when the modifiers have changed. * The method validates the modifiers and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null) { packages= froot.getChildren(); } } catch (JavaModelException e) { JavaPlugin.log(e); } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); if (fCurrPackage != null) { dialog.setInitialSelections(new Object[] { fCurrPackage }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root }); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ if (fCurrEnclosingType != null) { dialog.setInitialSelections(new Object[] { fCurrEnclosingType }); dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1)); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$ if (fSuperClass != null) { dialog.setFilter(fSuperClass.getElementName()); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= getTypeName(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { lineDelimiter= System.getProperty("line.separator", "\n"); String packStatement= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ";" + lineDelimiter + lineDelimiter; ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", packStatement, false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); String content= constructTypeStub(imports, lineDelimiter, parentCU); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 3)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); String content= constructTypeStub(imports, lineDelimiter, parentCU); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so types can be resolved correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1)); // add imports imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); ICompilationUnit cu= createdType.getCompilationUnit(); ISourceRange range; if (isInnerClass) { synchronized(cu) { cu.reconcile(); } range= createdType.getSourceRange(); } else { range= cu.getSourceRange(); } IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { String fileComment= getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. Only valid after createType has been invoked */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, IImportsStructure imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ buf.append(Signature.getSimpleName(typename)); if (fSuperClass != null) { imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass)); } else { imports.addImport(typename); } } } private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); imports.addImport(typename); buf.append(Signature.getSimpleName(typename)); if (i < last) { buf.append(','); } } } } /* * Called from createType to construct the source for this type */ private String constructTypeStub(IImportsStructure imports, String lineDelimiter, ICompilationUnit parentCU) { StringBuffer buf= new StringBuffer(); String typeComment= getTypeComment(parentCU); if (typeComment != null && typeComment.length() > 0) { buf.append(typeComment); buf.append(lineDelimiter); } int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append('{'); buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * Called from createType to allow adding methods, fielse, inner types ect for the newly created type. * Implementors can use the create methods on the new type. * Formatting will be applied to the content by the createType * @param newType The new type to add members to * @param imports To add the needed imports to. * @param monitor Progress monitor */ protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { // default implementation does nothing // example would be // String mainMathod= "public static void main(String[]) {}" // createdType.createMethod(main, null, false, null); } /** * Called from createType to get a file comment. By default the content of template * 'filecomment' is taken. * Returns source or null, if no file comment should be added */ protected String getFileComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doFileComments()) { return getTemplate("filecomment", parentCU); } return null; } /** * Called from createType to get a type comment. * Returns source or null, if no type comment should be added */ protected String getTypeComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doCreateComments()) { return getTemplate("typecomment", parentCU); } return null; } /** * Gets the template of the given name, evaluated in the context of a CU. */ protected String getTemplate(String name, ICompilationUnit parentCU) { Template[] templates= Templates.getInstance().getTemplates(); try { for (int i= 0; i < templates.length; i++) { if (name.equals(templates[i].getName())) { return JavaContext.evaluateTemplate(templates[i], parentCU); } } } catch (CoreException e) { JavaPlugin.log(e); } return null; } /** * Creates the bodies of all unimplemented methods or/and all constructors and adds them to the type * Can be used by implementors of NewTypeWizardPage to add method stub checkboxes. */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports); if (constructors != null) { for (int i= 0; i < constructors.length; i++) { newMethods.add(constructors[i]); } } } } if (doUnimplementedMethods) { String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports); if (unimplemented != null) { for (int i= 0; i < unimplemented.length; i++) { newMethods.add(unimplemented[i]); } } } IMethod[] createdMethods= new IMethod[newMethods.size()]; for (int i= 0; i < newMethods.size(); i++) { createdMethods[i]= type.createMethod((String) newMethods.get(i), null, false, null); } return createdMethods; } // ---- creation ---------------- /** * Returns a runnable that creates a type using the current settings. */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
12,101
Bug 12101 NewTypeWizardPage.createType crashes in non-ui thread
When performing the IRunnableWithProgress from NewTypeWizardPage.getRunnable, I get the stack-trace shown below. This is caused by a creation of the JavaTextTools object. Currently, my workaround is to call JavaPlugin.getDefault().getJavaTextTools() in the constructor of the class that I derive from NewTypeWizardPage. Stack trace: java/lang/Throwable.<init>()V java/lang/Throwable.<init>(Ljava/lang/String;)V java/lang/NullPointerException.<init>(Ljava/lang/String;)V org/eclipse/jdt/internal/ui/text/JavaColorManager.getColor(Lorg/eclipse/swt/graphics/RGB;)Lorg/eclipse/swt/graphics/Color; org/eclipse/jdt/internal/ui/text/JavaColorManager.getColor(Ljava/lang/String;)Lorg/eclipse/swt/graphics/Color; org/eclipse/jdt/internal/ui/text/AbstractJavaScanner.addToken(Ljava/lang/String;Ljava/lang/String;)V org/eclipse/jdt/internal/ui/text/AbstractJavaScanner.initialize()V org/eclipse/jdt/internal/ui/text/java/JavaCodeScanner.<init>(Lorg/eclipse/jdt/ui/text/IColorManager;Lorg/eclipse/jface/preference/IPreferenceStore;)V org/eclipse/jdt/ui/text/JavaTextTools.<init>(Lorg/eclipse/jface/preference/IPreferenceStore;)V org/eclipse/jdt/internal/ui/JavaPlugin.getJavaTextTools()Lorg/eclipse/jdt/ui/text/JavaTextTools; org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider$BufferFactory.internalCreateDocument(Lorg/eclipse/ui/IFileEditorInput;)Lorg/eclipse/jface/text/IDocument; org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider$BufferFactory.internalGetDocument(Lorg/eclipse/ui/IFileEditorInput;)Lorg/eclipse/jface/text/IDocument; org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider$BufferFactory.createBuffer(Lorg/eclipse/jdt/core/IOpenable;)Lorg/eclipse/jdt/core/IBuffer; org/eclipse/jdt/internal/core/CompilationUnit.getWorkingCopy(Lorg/eclipse/core/runtime/IProgressMonitor;Lorg/eclipse/jdt/core/IBufferFactory;)Lorg/eclipse/jdt/core/IJavaElement; org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.createElementInfo(Ljava/lang/Object;)Lorg/eclipse/ui/texteditor/AbstractDocumentProvider$ElementInfo; org/eclipse/ui/texteditor/AbstractDocumentProvider.connect(Ljava/lang/Object;)V org/eclipse/jdt/internal/corext/textmanipulation/TextBufferFactory.acquire(Lorg/eclipse/core/resources/IFile;)Lorg/eclipse/jdt/internal/corext/textmanipulation/TextBuffer; org/eclipse/jdt/internal/corext/textmanipulation/TextBuffer.acquire(Lorg/eclipse/core/resources/IFile;)Lorg/eclipse/jdt/internal/corext/textmanipulation/TextBuffer; org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.aquireTextBuffer()Lorg/eclipse/jdt/internal/corext/textmanipulation/TextBuffer; org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.create(ZLorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jdt/ui/wizards/NewTypeWizardPage.createType(Lorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jdt/ui/wizards/NewTypeWizardPage$1.run(Lorg/eclipse/core/runtime/IProgressMonitor;)V com/ibm/ive/jxe/buildfile/RunnableActionExecutor.run(Lorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jface/operation/ModalContext$ModalContextThread.run()V
resolved fixed
3cc706d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-03-29T18:55:12Z
2002-03-22T12:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.compiler.env.IConstants; 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.template.Template; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /** * <code>NewTypeWizardPage</code> contains controls and validation routines for a 'New Type WizardPage' * Implementors decide which components to add and to enable. Implementors can also * customize the validation code. * <code>NewTypeWizardPage</code> is intended to serve as base class of all wizards that create types. * Applets, Servlets, Classes, Interfaces... * See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an * example usage of NewTypeWizardPage. * @since 2.0 */ public abstract class NewTypeWizardPage extends NewContainerWizardPage { private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; public NewTypeWizardPage(boolean isClass, String pageName) { super(pageName); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the type page with a given * Java element as selection. To implement a different selection strategy do not call this * method or overwrite it. * @param elem The initial selection of this page or null if no * selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= JavaModelUtil.findPrimaryType(cu); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. Expects a GridLayout with at least 1 column. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. Expects a GridLayout with at least 4 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); } /** * Creates the controls for the enclosing type name field. Expects a GridLayout with at least 4 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { // #6891 Composite tabGroup= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; tabGroup.setLayout(layout); fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= getMaxFieldWidth(); gd.horizontalSpan= 2; c.setLayoutData(gd); Button button= fEnclosingTypeDialogField.getChangeControl(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); } /** * Creates the controls for the type name field. Expects a GridLayout with at least 2 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the modifiers radio/ceckbox buttons. Expects a GridLayout with at least 3 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); Control control= fAccMdfButtons.getSelectionButtonsGroup(composite); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); control= fOtherMdfButtons.getSelectionButtonsGroup(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. Expects a GridLayout with at least 3 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the superclass name field. Expects a GridLayout with at least 3 columns. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; gd.widthHint= getMaxFieldWidth(); } /** * Sets the focus on the type name. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /** * Called whenever a content of a field has changed. * Implementors of NewTypeWizardPage can hook in. * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Gets the text of package field. */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Gets the text of enclosing type field. */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * @return Returns <code>null</code> if the input could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the package fragment can be changed by the user */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the enclosing type corresponding to the current input. * @return Returns <code>null</code> if enclosing type is not selected or the input could not * be resolved. */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the enclosing type. * This will update model and the text of the control. * @param canBeModified Selects if the enclosing type can be changed by the user */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns <code>true</code> if the enclosing type selection check box is enabled. */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type selection checkbox. * @param canBeModified Selects if the enclosing type selection can be changed by the user */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Gets the type name. */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Gets the selected modifiers. * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= IConstants.AccPublic; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= IConstants.AccPrivate; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= IConstants.AccProtected; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= IConstants.AccAbstract; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= IConstants.AccFinal; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= IConstants.AccStatic; } return mdf; } /** * Sets the modifiers. * @param canBeModified Selects if the modifiers can be changed by the user * @see IConstants */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Gets the content of the super class text field. */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * @param canBeModified Selects if the super class can be changed by the user */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Gets the currently chosen super interfaces. * @return returns a list of String */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * @param canBeModified Selects if the modifiers can be changed by the user. * @param interfacesNames a list of String */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * Called when the package field has changed. * The method validates the package name and returns the status of the validation * This also updates the package fragment model. * Can be extended to add more validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { if (root.getJavaProject().exists() && packName.length() > 0) { try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= rootPath.append(packName.replace('.', '/')); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass } } fCurrPackage= root.getPackageFragment(packName); } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= getPackageText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Called when the enclosing type name has changed. * The method validates the enclosing type and returns the status of the validation * This also updates the enclosing type model. * Can be extended to add more validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= JavaModelUtil.findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type); if (!enclosingRoot.equals(root)) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$ } return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e); return status; } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Called when the superclass name has changed. * The method validates the superclass name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, sclassName); } } return type; } /** * Called when the list of super interface has changed. * The method validates the superinterfaces and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= JavaModelUtil.findType(root.getJavaProject(), intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, checking is an extra } } } return status; } /** * Called when the modifiers have changed. * The method validates the modifiers and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null) { packages= froot.getChildren(); } } catch (JavaModelException e) { JavaPlugin.log(e); } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); if (fCurrPackage != null) { dialog.setInitialSelections(new Object[] { fCurrPackage }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root }); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ if (fCurrEnclosingType != null) { dialog.setInitialSelections(new Object[] { fCurrEnclosingType }); dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1)); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$ if (fSuperClass != null) { dialog.setFilter(fSuperClass.getElementName()); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= getTypeName(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { lineDelimiter= System.getProperty("line.separator", "\n"); String packStatement= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ";" + lineDelimiter + lineDelimiter; ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", packStatement, false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); String content= constructTypeStub(imports, lineDelimiter, parentCU); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 3)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); String content= constructTypeStub(imports, lineDelimiter, parentCU); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so types can be resolved correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1)); // add imports imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); ICompilationUnit cu= createdType.getCompilationUnit(); ISourceRange range; if (isInnerClass) { synchronized(cu) { cu.reconcile(); } range= createdType.getSourceRange(); } else { range= cu.getSourceRange(); } IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { String fileComment= getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. Only valid after createType has been invoked */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, IImportsStructure imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ buf.append(Signature.getSimpleName(typename)); if (fSuperClass != null) { imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass)); } else { imports.addImport(typename); } } } private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); imports.addImport(typename); buf.append(Signature.getSimpleName(typename)); if (i < last) { buf.append(','); } } } } /* * Called from createType to construct the source for this type */ private String constructTypeStub(IImportsStructure imports, String lineDelimiter, ICompilationUnit parentCU) { StringBuffer buf= new StringBuffer(); String typeComment= getTypeComment(parentCU); if (typeComment != null && typeComment.length() > 0) { buf.append(typeComment); buf.append(lineDelimiter); } int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append('{'); buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * Called from createType to allow adding methods, fielse, inner types ect for the newly created type. * Implementors can use the create methods on the new type. * Formatting will be applied to the content by the createType * @param newType The new type to add members to * @param imports To add the needed imports to. * @param monitor Progress monitor */ protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { // default implementation does nothing // example would be // String mainMathod= "public static void main(String[]) {}" // createdType.createMethod(main, null, false, null); } /** * Called from createType to get a file comment. By default the content of template * 'filecomment' is taken. * Returns source or null, if no file comment should be added */ protected String getFileComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doFileComments()) { return getTemplate("filecomment", parentCU); } return null; } /** * Called from createType to get a type comment. * Returns source or null, if no type comment should be added */ protected String getTypeComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doCreateComments()) { return getTemplate("typecomment", parentCU); } return null; } /** * Gets the template of the given name, evaluated in the context of a CU. */ protected String getTemplate(String name, ICompilationUnit parentCU) { Template[] templates= Templates.getInstance().getTemplates(); try { for (int i= 0; i < templates.length; i++) { if (name.equals(templates[i].getName())) { return JavaContext.evaluateTemplate(templates[i], parentCU); } } } catch (CoreException e) { JavaPlugin.log(e); } return null; } /** * Creates the bodies of all unimplemented methods or/and all constructors and adds them to the type * Can be used by implementors of NewTypeWizardPage to add method stub checkboxes. */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports); if (constructors != null) { for (int i= 0; i < constructors.length; i++) { newMethods.add(constructors[i]); } } } } if (doUnimplementedMethods) { String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports); if (unimplemented != null) { for (int i= 0; i < unimplemented.length; i++) { newMethods.add(unimplemented[i]); } } } IMethod[] createdMethods= new IMethod[newMethods.size()]; for (int i= 0; i < newMethods.size(); i++) { String content= (String) newMethods.get(i) + "\n"; createdMethods[i]= type.createMethod(content, null, false, null); } return createdMethods; } // ---- creation ---------------- /** * Returns a runnable that creates a type using the current settings. */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
12,188
Bug 12188 Wrong Stylesheet Flag for Javadoc + impossible to deaktivate selection
javadoc: invalid flag: -stylsheet shouldbe: javadoc -stylesheetfile And it's im possible to deactivate the selecting of using the external Stylesheet.
resolved fixed
7944787
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-01T14:01:18Z
2002-03-23T19:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocOptionsManager.java
/* * (c) Copyright 2001 MyCorporation. * All Rights Reserved. */ 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.Iterator; import java.util.List; import java.util.StringTokenizer; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; 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.eclipse.jface.viewers.StructuredSelection; 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.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.launching.ExecutionArguments; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; 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; private IJavaProject fProject; private IFile fXmlfile; private StatusInfo fWizardStatus; private List fPackages; private String fAccess; private String fDocletpath; private String fDestination; private String fDocletname; private boolean fFromStandard; private String fStylesheet; private String fAdditionalParams; private String fOverview; private String fTitle; private String fJDocCommand; private String fSourcepath; private String fClasspath; private String fAntpath; private boolean fNotree; private boolean fNoindex; private boolean fSplitindex; private boolean fNonavbar; private boolean fNodeprecated; private boolean fNoDeprecatedlist; private boolean fAuthor; private boolean fVersion; public final static String PRIVATE= "private"; public final static String PROTECTED= "protected"; public final static String PACKAGE= "package"; public final static String PUBLIC= "public"; public final static String NOTREE= "notree"; public final static String NOINDEX= "noindex"; public final static String NONAVBAR= "nonavbar"; public final static String NODEPRECATED= "nodeprecated"; public final static String NODEPRECATEDLIST= "nodeprecatedlist"; public final static String VERSION= "version"; public final static String AUTHOR= "author"; public final static String SPLITINDEX= "splitindex"; public final static String STYLESHEETFILE= "stylesheetfile"; public final static String OVERVIEW= "overview"; public final static String DOCLETNAME= "docletname"; public final static String DOCLETPATH= "docletpath"; public final static String SOURCEPATH= "sourcepath"; public final static String CLASSPATH= "classpath"; public final static String DESTINATION= "destdir"; public final static String VISIBILITY= "access"; public final static String PACKAGENAMES= "packagenames"; public final static String EXTRAOPTIONS= "additionalparam"; public final static String JAVADOCCOMMAND= "javadoccommand"; public final static String TITLE= "doctitle"; public final String NAME= "name"; public final String PATH= "path"; public JavadocOptionsManager(IDialogSettings settings, IWorkspaceRoot root, ISelection selection) { this(null, settings, root, selection); } public JavadocOptionsManager(IFile xmlJavadocFile, IDialogSettings settings, IWorkspaceRoot root, ISelection currSelection) { Element element; this.fRoot= root; fJDocCommand= JavadocPreferencePage.getJavaDocCommand(); this.fXmlfile= xmlJavadocFile; this.fWizardStatus= new StatusInfo(); if(xmlJavadocFile!= null) { try { JavadocReader reader= new JavadocReader(xmlJavadocFile.getContents()); element= reader.readXML(); if (element == null) loadStore(settings, currSelection); else loadStore(element); } catch(CoreException e) { JavaPlugin.log(e); fWizardStatus.setWarning("Unable to run wizard from Ant file, defaults used..."); loadStore(settings, currSelection); } catch(IOException e) { JavaPlugin.log(e); fWizardStatus.setWarning("Error reading Ant file, defaults used..."); loadStore(settings, currSelection); } catch(SAXException e) { JavaPlugin.log(e); fWizardStatus.setWarning("Error reading Ant file, defaults used..."); loadStore(settings, currSelection); } }else loadStore(settings, currSelection); } private void loadStore(IDialogSettings settings, ISelection sel) { if(settings!= null){ fPackages= new ArrayList(); //getValidSelection will also find the project IStructuredSelection selection= getValidSelection(sel); fPackages= selection.toList(); fAccess= settings.get(VISIBILITY); if (fAccess == null) fAccess= PRIVATE; fFromStandard= false; fDocletpath= settings.get(DOCLETPATH); fDocletname= settings.get(DOCLETNAME); if (fDocletpath == null || fDocletname == null) { fFromStandard= true; fDocletname= fDocletname= ""; } //load a destination even if a custom doclet is being used fDestination= settings.get(DESTINATION); IPath path = null; if ((fDestination == null) || fDestination.equals("")) { path = null; if (fProject != null) { URL url = JavaDocLocations.getProjectJavadocLocation(fProject); //uses default if source is has http protocol if (url == null || !url.getProtocol().equals("file")) { fDestination = fProject .getProject() .getLocation() .addTrailingSeparator() .append("doc") .toOSString(); } else { //must do this to remove leading "/" File file = new File(url.getFile()); IPath tpath = new Path(file.getPath()); fDestination = tpath.toOSString(); } } else fDestination = ""; } if (fProject != null) { path= fProject.getProject().getLocation(); fAntpath= path.addTrailingSeparator().append("javadoc.xml").toOSString(); } else fAntpath= ""; fTitle= settings.get(TITLE); if(fTitle==null) fTitle=""; fStylesheet= settings.get(STYLESHEETFILE); if (fStylesheet == null) fStylesheet= ""; fAdditionalParams= settings.get(EXTRAOPTIONS); if (fAdditionalParams == null) fAdditionalParams= ""; fOverview= settings.get(OVERVIEW); if (fOverview == null) fOverview= ""; 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)); }else loadDefaults(sel); } private void loadDefaults(ISelection sel) { fPackages= new ArrayList(); IStructuredSelection selection= getValidSelection(sel); fPackages= selection.toList(); fAccess= PRIVATE; if (fProject == null) { fAntpath= ""; } else { IPath path= fProject.getProject().getLocation().addTrailingSeparator(); fAntpath= path.append("javadoc.xml").toOSString(); } //default destination fFromStandard= true; if (fProject != null) { URL url= JavaDocLocations.getProjectJavadocLocation(fProject); if (url != null && url.getProtocol().equals("file")) { File file= new File(url.getFile()); IPath tpath= new Path(file.getPath()); fDestination= tpath.toOSString(); } else { fDestination= fProject.getProject().getLocation().addTrailingSeparator().append("doc").toOSString(); } } else fDestination= ""; fDocletname=""; fDocletpath=""; fTitle= ""; fStylesheet= ""; fAdditionalParams= ""; fOverview= ""; fAuthor= true; fVersion= true; fNodeprecated= false; fNoDeprecatedlist= false; fNonavbar= false; fNoindex= false; fNotree= false; fSplitindex= true; } private void loadStore(Element element) { fAccess= element.getAttribute(VISIBILITY); if (!(fAccess.length() > 0)) fAccess= PRIVATE; //locate the project, set global variable fProject fSourcepath= element.getAttribute(SOURCEPATH); String token; if (!fSourcepath.equals("")) { int index= fSourcepath.indexOf(";"); if (index != -1) token= fSourcepath.substring(0, index); else token= fSourcepath; IContainer container= fRoot.getContainerForLocation(new Path(token)); if (container != null) { IProject p= container.getProject(); fProject= JavaCore.create(p); } } //Since the selected packages are stored we must locate the project fDestination= element.getAttribute(DESTINATION); fFromStandard= true; if (fDestination.equals("")) { NodeList list= element.getChildNodes(); for (int i= 0; i < list.getLength(); i++) { Node child= list.item(i); if (child.getNodeName().equals("doclet")) { fDocletpath= ((Element) child).getAttribute(PATH); fDocletname= ((Element) child).getAttribute(NAME); if (!(fDocletpath.equals("") && !fDocletname.equals(""))) fFromStandard= false; else fDocletname= fDocletpath =""; break; } } } //get all the package or type names //@Notice : Change settreechecked List names= new ArrayList(); String packagenames= element.getAttribute(PACKAGENAMES); if (packagenames != null) { StringTokenizer tokenizer= new StringTokenizer(packagenames, ","); while (tokenizer.hasMoreElements()) { names.add(tokenizer.nextElement()); } } //get tree elements fPackages= new ArrayList(); if (fProject != null) { try { for (int i= 0; i < names.size(); i++) { String name= (String) names.get(i); IJavaElement el= JavaModelUtil.findTypeContainer(fProject, name); fPackages.add(el); } } catch (JavaModelException e) { JavaPlugin.logErrorMessage(e.getMessage()); } } //set ant path fAntpath= fXmlfile.getLocation().toOSString(); // String antfilename= xmlfile.getName(); // try { // if(fProject != null) { // IPath path= fProject.getCorrespondingResource().getLocation(); // path= path.addTrailingSeparator().append(antfilename); // antpath= path.toOSString(); // } else antpath= antfilename; // } catch(JavaModelException e) { // antpath= antfilename; // } fStylesheet= element.getAttribute(STYLESHEETFILE); fTitle= element.getAttribute(TITLE); fAdditionalParams= element.getAttribute(EXTRAOPTIONS); fOverview= element.getAttribute(OVERVIEW); 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)); } //it is possible that the package list is empty public StatusInfo getWizardStatus() { return fWizardStatus; } public List getPackagenames() { return fPackages; } public String getAccess() { return fAccess; } public String getAntpath() { return fAntpath; } public boolean fromStandard() { return fFromStandard; } public String getDestination() { return fDestination; } public String getDocletPath() { return fDocletpath; } public String getDocletName() { return fDocletname; } public String getStyleSheet() { return fStylesheet; } public String getOverview() { return fOverview; } public String getAdditionalParams() { return fAdditionalParams; } public String getClasspath() { return fClasspath; } public String getSourcepath() { return fSourcepath; } public IWorkspaceRoot getRoot() { return fRoot; } public IJavaProject getJavaProject() { return this.fProject; } public String getTitle() { return fTitle; } public boolean getBoolean(String flag) { if (flag.equals(AUTHOR)) return fAuthor; else if (flag.equals(VERSION)) return fVersion; 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("")) return false; else { if (value.equals("true")) return true; else return false; } } public String[] createArgumentArray() { List args= new ArrayList(); args.add(fJDocCommand); if (fFromStandard) { args.add("-d"); args.add(fDestination); } else { if (!fAdditionalParams.equals("")) { ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); String[] argsArray= tokens.getProgramArgumentsArray(); for (int i= 0; i < argsArray.length; i++) { args.add(argsArray[i]); } } args.add("-doclet"); args.add(fDocletname); args.add("-docletpath"); args.add(fDocletpath); } args.add("-sourcepath"); args.add(fSourcepath); args.add("-classpath"); args.add(fClasspath); args.add("-" + fAccess); if (fFromStandard) { if (fVersion) args.add("-version"); if (fAuthor) args.add("-author"); if (fNonavbar) args.add("-nonavbar"); if (fNoindex) args.add("-noindex"); if (fNotree) args.add("-notree"); if (fNodeprecated) args.add("-nodeprecated"); if (fNoDeprecatedlist) args.add("-nodeprecatedlist"); if (fSplitindex) args.add("-splitindex"); if(!fTitle.equals("")) { args.add("-doctitle"); args.add(fTitle); } if (!fStylesheet.equals("")) { args.add("-stylsheet"); args.add(fStylesheet); } if (fFromStandard) { if (!fAdditionalParams.equals("")) { ExecutionArguments tokens = new ExecutionArguments("", fAdditionalParams); String[] argsArray = tokens.getProgramArgumentsArray(); for (int i = 0; i < argsArray.length; i++) { args.add(argsArray[i]); } } } } if (!fOverview.equals("")) { args.add("-overview"); args.add(fOverview); } Object[] str= fPackages.toArray(); for (int i= 0; i < str.length; i++) { String object= (String) str[i]; args.add(object); } return (String[]) args.toArray(new String[args.size()]); } public void createXML() { FileOutputStream objectStreamOutput= null; try { if (!fAntpath.equals("")) { File file= new File(fAntpath); IPath path= new Path(fAntpath); path= path.removeLastSegments(1); path.toFile().mkdirs(); objectStreamOutput= new FileOutputStream(file); JavadocWriter writer= new JavadocWriter(objectStreamOutput); writer.writeXML(this); } } catch (IOException e) { JavaPlugin.logErrorMessage(e.getMessage()); } finally { if (objectStreamOutput != null) { try { objectStreamOutput.close(); } catch (IOException e) {} } } } public IDialogSettings createDialogSettings() { IDialogSettings settings= new DialogSettings("javadoc"); if (!fFromStandard) { settings.put(DOCLETNAME, fDocletname); settings.put(DOCLETPATH, fDocletpath); } else settings.put(DESTINATION, fDestination); settings.put(VISIBILITY, fAccess); 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); if (!fAdditionalParams.equals("")) settings.put(EXTRAOPTIONS, fAdditionalParams); if (!fOverview.equals("")) settings.put(OVERVIEW, fOverview); if (!fStylesheet.equals("")) settings.put(STYLESHEETFILE, fStylesheet); if(!fTitle.equals("")) settings.put(TITLE, fTitle); return settings; } public void setAccess(String access) { this.fAccess= access; } public void setDestination(String destination) { this.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 setAntpath(String antpath) { this.fAntpath= antpath; } public void setClasspath(String classpath) { this.fClasspath= classpath; } public void setSourcepath(String sourcepath) { this.fSourcepath= sourcepath; } public void setPackagenames(List packagenames) { this.fPackages= packagenames; } public void setRoot(IWorkspaceRoot root) { this.fRoot= root; } public void setProject(IJavaProject project) { this.fProject= project; } public void setFromStandard(boolean fromStandard) { this.fFromStandard= fromStandard; } public void setTitle(String title) { this.fTitle= title; } public void setBoolean(String flag, boolean value) { if (flag.equals(AUTHOR)) this.fAuthor= 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; } private IStructuredSelection getValidSelection(ISelection currentSelection) { if (currentSelection instanceof IStructuredSelection) { IStructuredSelection structuredSelection= (IStructuredSelection) currentSelection; if (structuredSelection.isEmpty()) { currentSelection= JavaPlugin.getActiveWorkbenchWindow().getSelectionService().getSelection(); if (currentSelection instanceof IStructuredSelection) structuredSelection= (IStructuredSelection) currentSelection; } List selectedElements= new ArrayList(structuredSelection.size()); Iterator iter= structuredSelection.iterator(); //this method will also find the project for default //destination and ant generation paths getProject(selectedElements, iter); if (!selectedElements.isEmpty()) { return new StructuredSelection(selectedElements); } } if (fProject != null) return new StructuredSelection(fProject); return StructuredSelection.EMPTY; } private void getProject(List selectedElements, Iterator iter) { fProject= null; while (iter.hasNext()) { Object selectedElement= iter.next(); IJavaElement elem= getSelectableJavaElement(selectedElement); if (elem != null) { IJavaProject jproj= elem.getJavaProject(); if (fProject == null || fProject.equals(jproj)) { selectedElements.add(elem); fProject= jproj; break; } } } if (fProject == null) { Object[] roots= fRoot.getProjects(); for (int i= 0; i < roots.length; i++) { IProject p= (IProject) roots[i]; IJavaProject iJavaProject= JavaCore.create(p); if (getValidProject(iJavaProject)) { fProject= iJavaProject; break; } } } } 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) JavaModelUtil.findElementOfKind(je, IJavaElement.COMPILATION_UNIT); if (cu != null) { if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } IType primaryType= JavaModelUtil.findPrimaryType(cu); if (primaryType != null) { return primaryType; } } } } 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; } }
9,258
Bug 9258 Failed to execute runnable - NullPointerException
Had just typed in java code: "Response answer = message." Didn't even press Crtl-space Dialog popped up with "An internal error has occurred. Failed to execute runnable (java.lang.NullPointerException)" All the java code is OK, and this happens if I go back and delete the "age." and type it in again. Sorry this is not very specific - I can send you the code if you want... Log: Log: Thu Feb 07 16:45:53 GMT 2002 1 org.eclipse.core.resources 4 Unhandled exception caught in event loop. Log: Thu Feb 07 16:45:53 GMT 2002 4 org.eclipse.ui 0 Failed to execute runnable (java.lang.NullPointerException) org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.NullPointerException) at org.eclipse.swt.SWT.error(SWT.java:1887) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:96) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1390) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:844) at org.eclipse.ui.internal.Workbench.run(Workbench.java:827) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:878) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:321) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
resolved fixed
be729b5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-01T14:49:32Z
2002-02-07T16:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ResultCollector.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import org.eclipse.core.resources.IMarker; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.ICompletionRequestor; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; /** * Bin to collect the proposal of the infrastructure on code assist in a java text. */ public class ResultCollector implements ICompletionRequestor { private class ProposalComparator implements Comparator { public int compare(Object o1, Object o2) { ICompletionProposal c1= (ICompletionProposal) o1; ICompletionProposal c2= (ICompletionProposal) o2; return c1.getDisplayString().compareToIgnoreCase(c2.getDisplayString()); } }; private final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' }; private final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' }; private final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' }; private final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';' }; private ArrayList fFields= new ArrayList(), fKeywords= new ArrayList(), fLabels= new ArrayList(), fMethods= new ArrayList(), fModifiers= new ArrayList(), fPackages= new ArrayList(), fTypes= new ArrayList(), fVariables= new ArrayList(); private IProblem fLastProblem; private IJavaProject fJavaProject; private ICompilationUnit fCompilationUnit; // set when imports can be added private int fCodeAssistOffset; private ImageDescriptorRegistry fRegistry= JavaPlugin.getImageDescriptorRegistry(); private ArrayList[] fResults = new ArrayList[] { fVariables, fFields, fMethods, fTypes, fKeywords, fModifiers, fLabels, fPackages }; private int fUserReplacementLength; /* * Is eating code assist enabled or disabled? PR #3666 * When eating is enabled, JavaCompletionProposal must be revisited: PR #5533 */ private boolean fPreventEating= true; /* * @see ICompletionRequestor#acceptClass */ public void acceptClass(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end) { ImageDescriptor descriptor= JavaPluginImages.DESC_OBJS_CLASS; if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info)); } /* * @see ICompletionRequestor#acceptError(IProblem) */ public void acceptError(IProblem error) { fLastProblem= error; } /* * @see ICompletionRequestor#acceptField */ public void acceptField( char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int start, int end) { ImageDescriptor descriptor= getMemberDescriptor(modifiers); if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(name); if (typeName.length > 0) { nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(typeName); } if (declaringTypeName != null && declaringTypeName.length > 0) { nameBuffer.append(" - "); //$NON-NLS-1$ nameBuffer.append(declaringTypeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString()); proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name)); proposal.setTriggerCharacters(VAR_TRIGGER); fFields.add(proposal); } /* * @see ICompletionRequestor#acceptInterface */ public void acceptInterface(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end) { ImageDescriptor descriptor= JavaPluginImages.DESC_OBJS_INTERFACE; if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info)); } /* * @see ICompletionRequestor#acceptAnonymousType(char[], char[], char[][], char[][], char[][], char[], int, int, int) */ public void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int modifiers, int completionStart, int completionEnd) { JavaCompletionProposal proposal= createAnonymousTypeCompletion(superTypePackageName, superTypeName, parameterTypeNames, parameterNames, completionName, completionStart, completionEnd); proposal.setProposalInfo(new ProposalInfo(fJavaProject, superTypePackageName, superTypeName)); fTypes.add(proposal); } /* * @see ICompletionRequestor#acceptKeyword */ public void acceptKeyword(char[] keyword, int start, int end) { String kw= new String(keyword); fKeywords.add(createCompletion(start, end, kw, null, kw)); } /* * @see ICompletionRequestor#acceptLabel */ public void acceptLabel(char[] labelName, int start, int end) { String ln= new String(labelName); fLabels.add(createCompletion(start, end, ln, null, ln)); } /* * @see ICompletionRequestor#acceptLocalVariable */ public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int start, int end) { StringBuffer buf= new StringBuffer(); buf.append(name); if (typeName != null) { buf.append(" "); //$NON-NLS-1$ buf.append(typeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(name), null, buf.toString()); proposal.setTriggerCharacters(VAR_TRIGGER); fVariables.add(proposal); } private String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) { StringBuffer buf = new StringBuffer(); if (parameterTypeNames != null) { for (int i = 0; i < parameterTypeNames.length; i++) { if (i > 0) { buf.append(','); buf.append(' '); } buf.append(parameterTypeNames[i]); if (parameterNames[i] != null) { buf.append(' '); buf.append(parameterNames[i]); } } } return buf.toString(); } /* * @see ICompletionRequestor#acceptMethod(char[], char[], char[], char[][], char[][], char[][], char[], char[], char[], int, int, int) */ public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) { JavaCompletionProposal proposal= createMethodCallCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end); proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0)); boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')'); ProposalContextInformation contextInformation= null; if (hasOpeningBracket && parameterTypeNames.length > 0) { contextInformation= new ProposalContextInformation(); contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames)); contextInformation.setContextDisplayString(proposal.getDisplayString()); contextInformation.setImage(proposal.getImage()); proposal.setContextInformation(contextInformation); } boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0); char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS; proposal.setTriggerCharacters(triggers); if (userMustCompleteParameters) { // set the cursor before the closing bracket proposal.setCursorPosition(completionName.length - 1); } fMethods.add(proposal); } /* * @see ICompletionRequestor#acceptModifier */ public void acceptModifier(char[] modifier, int start, int end) { String mod= new String(modifier); fModifiers.add(createCompletion(start, end, mod, null, mod)); } /* * @see ICompletionRequestor#acceptPackage */ public void acceptPackage(char[] packageName, char[] completionName, int start, int end) { fPackages.add(createCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_PACKAGE, new String(packageName))); } /* * @see ICompletionRequestor#acceptType */ public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end) { ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_CLASS, new String(typeName), new String(packageName), info)); } /* * @see ICodeCompletionRequestor#acceptMethodDeclaration(char[], char[], char[], char[][], char[][], char[][], char[], char[], char[], int, int, int) */ public void acceptMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) { // XXX: To be revised JavaCompletionProposal proposal= createMethodDeclarationCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end); fMethods.add(proposal); } /* * @see ICodeCompletionRequestor#acceptVariableName(char[], char[], char[], char[], int, int) */ public void acceptVariableName(char[] typePackageName, char[] typeName, char[] name, char[] completionName, int start, int end) { // XXX: To be revised StringBuffer buf= new StringBuffer(); buf.append(name); if (typeName != null && typeName.length > 0) { buf.append(" - "); //$NON-NLS-1$ buf.append(typeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), null, buf.toString()); proposal.setTriggerCharacters(VAR_TRIGGER); fVariables.add(proposal); } public String getErrorMessage() { if (fLastProblem != null) return fLastProblem.getMessage(); return ""; //$NON-NLS-1$ } public JavaCompletionProposal[] getResults() { ArrayList result= new ArrayList(); ProposalComparator comperator= new ProposalComparator(); for (int i= 0; i < fResults.length; i++) { ArrayList bucket = fResults[i]; int size= bucket.size(); if (size == 1) { result.add(bucket.get(0)); } else if (size > 1) { Object[] sortedBucket = new Object[size]; bucket.toArray(sortedBucket); Arrays.sort(sortedBucket, comperator); for (int j= 0; j < sortedBucket.length; j++) result.add(sortedBucket[j]); } } return (JavaCompletionProposal[]) result.toArray(new JavaCompletionProposal[result.size()]); } private JavaCompletionProposal createMethodCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) { ImageDescriptor descriptor= getMemberDescriptor(modifiers); if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(name); nameBuffer.append('('); if (parameterTypeNames.length > 0) { nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames)); } nameBuffer.append(')'); if (returnTypeName.length > 0) { nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(returnTypeName); } if (declaringTypeName.length > 0) { nameBuffer.append(" - "); //$NON-NLS-1$ nameBuffer.append(declaringTypeName); } return createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString()); } protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) { return createMethodCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end); } protected JavaCompletionProposal createMethodDeclarationCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) { return createMethodCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end); } protected JavaCompletionProposal createAnonymousTypeCompletion(char[] declaringTypePackageName, char[] declaringTypeName, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int start, int end) { StringBuffer declTypeBuf= new StringBuffer(); if (declaringTypePackageName.length > 0) { declTypeBuf.append(declaringTypePackageName); declTypeBuf.append('.'); } declTypeBuf.append(declaringTypeName); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(declaringTypeName); nameBuffer.append('('); if (parameterTypeNames.length > 0) { nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames)); } nameBuffer.append(')'); nameBuffer.append(" "); nameBuffer.append(JavaTextMessages.getString("ResultCollector.anonymous_type")); //$NON-NLS-1$ int length= end - start; return new AnonymousTypeCompletionProposal(fJavaProject, fCompilationUnit, start, length, new String(completionName), nameBuffer.toString(), declTypeBuf.toString()); } protected JavaCompletionProposal createTypeCompletion(int start, int end, String completion, ImageDescriptor descriptor, String typeName, String containerName, ProposalInfo proposalInfo) { IImportDeclaration importDeclaration= null; if (containerName != null && fCompilationUnit != null) { if (completion.equals(JavaModelUtil.concatenateName(containerName, typeName))) { importDeclaration= fCompilationUnit.getImport(completion); completion= typeName; } } StringBuffer buf= new StringBuffer(typeName); if (containerName != null) { buf.append(" - "); //$NON-NLS-1$ if (containerName.length() > 0) { buf.append(containerName); } else { buf.append(JavaTextMessages.getString("ResultCollector.default_package")); } } String name= buf.toString(); JavaCompletionProposal proposal= createCompletion(start, end, completion, descriptor, name); proposal.setImportDeclaration(importDeclaration); proposal.setProposalInfo(proposalInfo); proposal.setTriggerCharacters(TYPE_TRIGGERS); return proposal; } protected ImageDescriptor getMemberDescriptor(int modifiers) { if (Flags.isPublic(modifiers)) { return JavaPluginImages.DESC_MISC_PUBLIC; } else if (Flags.isProtected(modifiers)) { return JavaPluginImages.DESC_MISC_PROTECTED; } else if (Flags.isPrivate(modifiers)) { return JavaPluginImages.DESC_MISC_PRIVATE; } else { return JavaPluginImages.DESC_MISC_DEFAULT; } } protected ImageDescriptor getDeprecatedDescriptor(ImageDescriptor descriptor) { Point size= new Point(16, 16); return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.WARNING, size); } protected JavaCompletionProposal createCompletion(int start, int end, String completion, ImageDescriptor descriptor, String name) { int length; if (fUserReplacementLength == -1) { length= fPreventEating ? fCodeAssistOffset - start : end - start; } else { length= fUserReplacementLength; // extend length to begin at start if (start < fCodeAssistOffset) { length+= fCodeAssistOffset - start; } } Image icon= (descriptor == null) ? null : fRegistry.get(descriptor); return new JavaCompletionProposal(completion, start, length, icon, name); } /** * Specifies the context of the code assist operation. * @param codeAssistOffset The Offset on which the code assist will be called. * Used to modify the offsets of the created proposals. ('Non Eating') * @param jproject The Java project to which the underlying source belongs. * Needed to find types referred. * @param cu The compilation unit that is edited. Used to add import statements. * Can be <code>null</code> if no import statements should be added. */ public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) { fJavaProject= jproject; fCompilationUnit= cu; fCodeAssistOffset= codeAssistOffset; fUserReplacementLength= -1; fLastProblem= null; for (int i= 0; i < fResults.length; i++) fResults[i].clear(); } /** * If the replacement length is set, it overrides the length returned from * the content assist infrastructure. * Use this setting if code assist is called with a none empty selection. */ public void setReplacementLength(int length) { fUserReplacementLength= length; } /** * If set, proposals created will not remove characters after the code assist position * @param preventEating The preventEating to set */ public void setPreventEating(boolean preventEating) { fPreventEating= preventEating; } }
8,808
Bug 8808 Class folder: Must use create to add an existing folder
Build I20020129 "Add Folders..." does not show the project itself. I have to do the following trick to add an existing folder as class folder: Press "Create folder" Enter the name of the existing folder (hopfully it's in the project root :-) Voila BTW: I can't do this a second time - the UI tells me it already exists - which is OK. To be consistent with other dialogs "Create Folder" should always warn about existing projects.
resolved fixed
cccdf8f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-01T17:38:47Z
2002-01-31T09:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.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 java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.IUIConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class LibrariesWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; private IJavaProject fCurrJProject; private ListDialogField fLibrariesList; private IWorkspaceRoot fWorkspaceRoot; private IDialogSettings fDialogSettings; private Control fSWTControl; public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) { fClassPathList= classPathList; fWorkspaceRoot= root; fSWTControl= null; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addnew.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addexisting.button"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$ /* 3 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$ /* 5 */ null, /* 6 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.setsource.button"), //$NON-NLS-1$ /* 7 */ null, /* 8 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.remove.button") //$NON-NLS-1$ }; LibrariesAdapter adapter= new LibrariesAdapter(); fLibrariesList= new ListDialogField(adapter, buttonLabels, new CPListLabelProvider()); fLibrariesList.setDialogFieldListener(adapter); fLibrariesList.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.libraries.label")); //$NON-NLS-1$ fLibrariesList.setRemoveButtonIndex(8); //$NON-NLS-1$ fLibrariesList.enableButton(6, false); fLibrariesList.setViewerSorter(new CPListElementSorter()); } public void init(IJavaProject jproject) { fCurrJProject= jproject; updateLibrariesList(); } private void updateLibrariesList() { List cpelements= fClassPathList.getElements(); List libelements= new ArrayList(cpelements.size()); int nElements= cpelements.size(); for (int i= 0; i < nElements; i++) { CPListElement cpe= (CPListElement)cpelements.get(i); int kind= cpe.getEntryKind(); if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) { libelements.add(cpe); } } fLibrariesList.setElements(libelements); } // -------- ui creation public Control getControl(Composite parent) { PixelConverter converter= new PixelConverter(parent); Composite composite= new Composite(parent, SWT.NONE); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true, SWT.DEFAULT, SWT.DEFAULT); LayoutUtil.setHorizontalGrabbing(fLibrariesList.getListControl(null)); int buttonBarWidth= converter.convertWidthInCharsToPixels(24); fLibrariesList.setButtonsMinWidth(buttonBarWidth); fLibrariesList.getTableViewer().setSorter(new CPListElementSorter()); fSWTControl= composite; return composite; } private Shell getShell() { if (fSWTControl != null) { return fSWTControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private class LibrariesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { libaryPageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) { libaryPageSelectionChanged(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { libaryPageDialogFieldChanged(field); } } private void libaryPageCustomButtonPressed(DialogField field, int index) { CPListElement[] libentries= null; switch (index) { case 0: /* add new */ libentries= createNewClassContainer(); break; case 1: /* add existing */ libentries= chooseClassContainers(); break; case 2: /* add jar */ libentries= chooseJarFiles(); break; case 3: /* add external jar */ libentries= chooseExtJarFiles(); break; case 4: /* add variable */ libentries= chooseVariableEntries(); break; case 6: /* set source attachment */ List selElements= fLibrariesList.getSelectedElements(); CPListElement selElement= (CPListElement) selElements.get(0); SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), selElement.getClasspathEntry()); if (dialog.open() == dialog.OK) { selElement.setSourceAttachment(dialog.getSourceAttachmentPath(), dialog.getSourceAttachmentRootPath()); selElement.setJavadocLocation(dialog.getJavadocLocation()); fLibrariesList.refresh(); fClassPathList.refresh(); } break; } if (libentries != null) { int nElementsChosen= libentries.length; // remove duplicates List cplist= fLibrariesList.getElements(); List elementsToAdd= new ArrayList(nElementsChosen); for (int i= 0; i < nElementsChosen; i++) { CPListElement curr= libentries[i]; if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) { elementsToAdd.add(curr); addAttachmentsFromExistingLibs(curr); } } fLibrariesList.addElements(elementsToAdd); fLibrariesList.postSetSelection(new StructuredSelection(libentries)); } } private void libaryPageSelectionChanged(DialogField field) { List selElements= fLibrariesList.getSelectedElements(); fLibrariesList.enableButton(6, canDoSourceAttachment(selElements)); } private void libaryPageDialogFieldChanged(DialogField field) { if (fCurrJProject != null) { // already initialized updateClasspathList(); } } private boolean canDoSourceAttachment(List selElements) { if (selElements != null && selElements.size() == 1) { CPListElement elem= (CPListElement) selElements.get(0); return (!(elem.getResource() instanceof IFolder)); } return false; } private void updateClasspathList() { List projelements= fLibrariesList.getElements(); boolean remove= false; List cpelements= fClassPathList.getElements(); // backwards, as entries will be deleted for (int i= cpelements.size() - 1; i >= 0; i--) { CPListElement cpe= (CPListElement)cpelements.get(i); int kind= cpe.getEntryKind(); if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) { if (!projelements.remove(cpe)) { cpelements.remove(i); remove= true; } } } for (int i= 0; i < projelements.size(); i++) { cpelements.add(projelements.get(i)); } if (remove || (projelements.size() > 0)) { fClassPathList.setElements(cpelements); } } private CPListElement[] createNewClassContainer() { String title= NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.title"); //$NON-NLS-1$ IProject currProject= fCurrJProject.getProject(); NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers()); IPath projpath= currProject.getFullPath(); dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$ int ret= dialog.open(); if (ret == dialog.OK) { IFolder folder= dialog.getFolder(); return new CPListElement[] { newCPLibraryElement(folder) }; } return null; } private CPListElement[] chooseClassContainers() { Class[] acceptedClasses= new Class[] { IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); acceptedClasses= new Class[] { IProject.class, IFolder.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource) elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private CPListElement[] chooseJarFiles() { Class[] acceptedClasses= new Class[] { IFile.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource)elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private IContainer[] getUsedContainers() { ArrayList res= new ArrayList(); if (fCurrJProject.exists()) { try { IPath outputLocation= fCurrJProject.getOutputLocation(); if (outputLocation != null) { IResource resource= fWorkspaceRoot.findMember(outputLocation); if (resource instanceof IContainer) { res.add(resource); } } } catch (JavaModelException e) { // ignore it here, just log JavaPlugin.log(e.getStatus()); } } List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IContainer) { res.add(resource); } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } private IFile[] getUsedJARFiles() { List res= new ArrayList(); List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IFile) { res.add(resource); } } return (IFile[]) res.toArray(new IFile[res.size()]); } private CPListElement newCPLibraryElement(IResource res) { return new CPListElement(IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res); }; private CPListElement[] chooseExtJarFiles() { String lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR); if (lastUsedPath == null) { lastUsedPath= ""; //$NON-NLS-1$ } FileDialog dialog= new FileDialog(getShell(), SWT.MULTI); dialog.setText(NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(lastUsedPath); String res= dialog.open(); if (res == null) { return null; } String[] fileNames= dialog.getFileNames(); int nChosen= fileNames.length; IPath filterPath= new Path(dialog.getFilterPath()); CPListElement[] elems= new CPListElement[nChosen]; for (int i= 0; i < nChosen; i++) { IPath path= filterPath.append(fileNames[i]).makeAbsolute(); elems[i]= new CPListElement(IClasspathEntry.CPE_LIBRARY, path, null); } fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString()); return elems; } private CPListElement[] chooseVariableEntries() { ArrayList existingPaths= new ArrayList(); for (int i= 0; i < fLibrariesList.getSize(); i++) { CPListElement elem= (CPListElement) fLibrariesList.getElement(i); if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { existingPaths.add(elem.getPath()); } } VariableSelectionDialog dialog= new VariableSelectionDialog(getShell(), existingPaths); if (dialog.open() == dialog.OK) { IPath path= dialog.getVariable(); CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, path, null); IPath resolvedPath= JavaCore.getResolvedVariablePath(path); elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().isFile()); return new CPListElement[] { elem }; } return null; } private void addAttachmentsFromExistingLibs(CPListElement elem) { try { IJavaModel jmodel= fCurrJProject.getJavaModel(); IJavaProject[] jprojects= jmodel.getJavaProjects(); for (int i= 0; i < jprojects.length; i++) { IJavaProject curr= jprojects[i]; if (!curr.equals(fCurrJProject)) { IClasspathEntry[] entries= curr.getRawClasspath(); for (int k= 0; k < entries.length; k++) { IClasspathEntry entry= entries[k]; if (entry.getEntryKind() == elem.getEntryKind() && entry.getPath().equals(elem.getPath())) { IPath attachPath= entry.getSourceAttachmentPath(); if (attachPath != null && !attachPath.isEmpty()) { elem.setSourceAttachment(attachPath, entry.getSourceAttachmentRootPath()); return; } } } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } // a dialog to set the source attachment properties private class VariableSelectionDialog extends StatusDialog implements IStatusChangeListener { private VariableSelectionBlock fVariableSelectionBlock; public VariableSelectionDialog(Shell parent, List existingPaths) { super(parent); setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.title")); //$NON-NLS-1$ String initVar= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTVARIABLE); fVariableSelectionBlock= new VariableSelectionBlock(this, existingPaths, null, initVar, false); } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.VARIABLE_SELECTION_DIALOG); } /* * @see StatusDialog#createDialogArea() */ protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Label message= new Label(composite, SWT.WRAP); message.setText(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.message")); //$NON-NLS-1$ message.setLayoutData(new GridData()); Control inner= fVariableSelectionBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } /* * @see Dialog#okPressed() */ protected void okPressed() { fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTVARIABLE, getVariable().segment(0)); super.okPressed(); } /* * @see IStatusChangeListener#statusChanged() */ public void statusChanged(IStatus status) { updateStatus(status); } public IPath getVariable() { return fVariableSelectionBlock.getVariablePath(); } } // a dialog to set the source attachment properties private class SourceAttachmentDialog extends StatusDialog implements IStatusChangeListener { private SourceAttachmentBlock fSourceAttachmentBlock; public SourceAttachmentDialog(Shell parent, IClasspathEntry entry) { super(parent); setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.SourceAttachmentDialog.title", entry.getPath().toString())); //$NON-NLS-1$ fSourceAttachmentBlock= new SourceAttachmentBlock(fWorkspaceRoot, this, entry); } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.SOURCE_ATTACHMENT_DIALOG); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Control inner= fSourceAttachmentBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } public void statusChanged(IStatus status) { updateStatus(status); } public IPath getSourceAttachmentPath() { return fSourceAttachmentBlock.getSourceAttachmentPath(); } public IPath getSourceAttachmentRootPath() { return fSourceAttachmentBlock.getSourceAttachmentRootPath(); } public URL getJavadocLocation() { return fSourceAttachmentBlock.getJavadocLocation(); } } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { return fLibrariesList.getSelectedElements(); } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { for (int i= selElements.size()-1; i >= 0; i--) { CPListElement curr= (CPListElement) selElements.get(i); int kind= curr.getEntryKind(); if (kind != IClasspathEntry.CPE_LIBRARY && kind != IClasspathEntry.CPE_VARIABLE) { selElements.remove(i); } } fLibrariesList.selectElements(new StructuredSelection(selElements)); } }
9,601
Bug 9601 Open external JavaDoc does not work correctly with Netscape 4.76
Test Case: 0) Have Netscape 4.76 registered as system default browser. 1) Have JRE_LIB of 20020212-I in workspace 2) Context Menu -> Properties: Attach documentation location: 'M:\java\jdk1.2\docs\api\' 3) Verify that Netscape is not running. 4) Context Menu -> Open External Javadoc 5) Observer the error dialog: Cannot find the file 'file:/M:/JAVA/jdk1.2/docs/api/overview-summary.html' ... However, the html file is actually displayed. 6) Close the error dialog. 7) Browse to some other page in Netscape. 8) Do step 4) again. 9) The correct page is displayed w/o an error dialog.
resolved fixed
9911c44
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T09:36:17Z
2002-02-13T14:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OpenExternalJavadocAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.actions; import java.io.File; import java.net.URL; import java.text.MessageFormat; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.help.IHelpResource; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; /** * On a selected member; opens the Javadoc in an external browser (if existing) */ public class OpenExternalJavadocAction extends Action implements IUpdate, IObjectActionDelegate { private StructuredSelectionProvider fSelectionProvider; /** * Use only for IWorkbenchWindowActionDelegates! */ public OpenExternalJavadocAction() { this(null); } public OpenExternalJavadocAction(StructuredSelectionProvider provider) { super(); setText("Open E&xternal Javadoc@Shift+F2"); setDescription("Opens the Javadoc of the selected element in an external browser"); setToolTipText("Opens the Javadoc of the selected element in an external browser"); fSelectionProvider= provider; } public void update() { setEnabled(canOperateOn()); } private boolean canOperateOn() { if (fSelectionProvider != null) { IStructuredSelection selection= fSelectionProvider.getSelection(StructuredSelectionProvider.FLAGS_GET_EDITOR_INPUT); return selection.size() == 1; } return false; } private Object getSelectedElement() { if (fSelectionProvider == null) { return null; } IStructuredSelection selection= fSelectionProvider.getSelection(StructuredSelectionProvider.FLAGS_DO_CODERESOLVE | StructuredSelectionProvider.FLAGS_GET_EDITOR_INPUT); if (selection.size() != 1) return null; return selection.getFirstElement(); } public void run() { Object selected= getSelectedElement(); if (!(selected instanceof IJavaElement)) { return; } IJavaElement jelem= (IJavaElement) selected; Shell shell= JavaPlugin.getActiveWorkbenchShell(); try { String labelName= JavaElementLabels.getElementLabel(jelem, JavaElementLabels.M_PARAMETER_TYPES); URL baseURL= JavaDocLocations.getJavadocBaseLocation(jelem); if (baseURL == null) { IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(jelem); if (root != null && root.getKind() == IPackageFragmentRoot.K_BINARY) { String message= "The documentation location for ''{0}'' has not been configured. For elements from libraries specify the Javadoc location URL on the property page of the parent JAR (''{1}'')."; showError(shell, MessageFormat.format(message, new String[] { labelName, root.getElementName() })); } else { IJavaElement annotatedElement= jelem.getJavaProject(); String message= "The documentation location for ''{0}'' has not been configured. For elements from source specify the Javadoc location URL on the property page of the parent project (''{1}'')."; showError(shell, MessageFormat.format(message, new String[] { labelName, annotatedElement.getElementName() })); } return; } if ("file".equals(baseURL.getProtocol())) { URL noRefURL= JavaDocLocations.getJavaDocLocation(jelem, false); if (!(new File(noRefURL.getFile())).isFile()) { String message= "No documentation available for ''{0}'' in ''{1}''."; showError(shell, MessageFormat.format(message, new String[] { labelName, baseURL.toExternalForm() })); return; } } URL url= JavaDocLocations.getJavaDocLocation(jelem, true); if (url != null) { openInBrowser(url, shell); } } catch (CoreException e) { JavaPlugin.log(e); showError(shell, "Opening Javadoc failed. See log for details."); } } /* * @see IActionDelegate#run(IAction) */ public void run(IAction action) { run(); } /* * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { } /* * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { fSelectionProvider= StructuredSelectionProvider.createFrom(targetPart.getSite().getWorkbenchWindow().getSelectionService()); } private static boolean webBrowserOpened = false; /** * Copied from AboutPluginsDialog.openMoreInfo */ public static void openInBrowser(final URL url, final Shell shell) { IHelpResource helpResource= new IHelpResource() { public String getHref() { return url.toExternalForm(); } public String getLabel() { return url.toExternalForm(); } }; WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource); } private static void showError(final Shell shell, final String message) { Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(shell, "Open External Javadoc", message); } }); } }
11,306
Bug 11306 New class wizard launches simple project wizard
1. In a new workspace, press the "New Class" button in the Java perspective. 2. Since there are no existing projects, the dialog prompts the user to create a new project. This is very handy. However, if the user answers yes, the resulting dialog is the first page of the generic new project wizard. The Java Class wizard should open the Java Project wizard.
resolved fixed
46595e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T10:02:32Z
2002-03-13T22:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/AbstractOpenWizardAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.util.Iterator; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.ui.IWorkbenchWizard; import org.eclipse.ui.actions.NewProjectAction; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.util.PixelConverter; public abstract class AbstractOpenWizardAction extends Action implements IWorkbenchWindowActionDelegate { private Class[] fActivatedOnTypes; private boolean fAcceptEmptySelection; private boolean fNoChecking; /** * Creates a AbstractOpenWizardAction. * @param label The label of the action * @param acceptEmptySelection Specifies if the action allows an empty selection */ public AbstractOpenWizardAction(String label, boolean acceptEmptySelection) { this(label, null, acceptEmptySelection); } /** * Creates a AbstractOpenWizardAction. * @param label The label of the action * @param activatedOnTypes The action is only enabled when all objects in the selection * are of the given types. <code>null</code> will allow all types. * @param acceptEmptySelection Specifies if the action allows an empty selection */ public AbstractOpenWizardAction(String label, Class[] activatedOnTypes, boolean acceptEmptySelection) { super(label); fActivatedOnTypes= activatedOnTypes; fAcceptEmptySelection= acceptEmptySelection; fNoChecking= false; } /** * Creates a AbstractOpenWizardAction with no restrictions on types, and does allow * an empty selection. */ protected AbstractOpenWizardAction() { fActivatedOnTypes= null; fAcceptEmptySelection= true; fNoChecking= true; } protected IWorkbench getWorkbench() { return JavaPlugin.getDefault().getWorkbench(); } private boolean isOfAcceptedType(Object obj) { if (fActivatedOnTypes != null) { for (int i= 0; i < fActivatedOnTypes.length; i++) { if (fActivatedOnTypes[i].isInstance(obj)) { return true; } } return false; } return true; } private boolean isEnabled(IStructuredSelection selection) { Iterator iter= selection.iterator(); while (iter.hasNext()) { Object obj= iter.next(); if (!isOfAcceptedType(obj) || !shouldAcceptElement(obj)) { return false; } } return true; } /** * Can be overridden to add more checks. * obj is guaranteed to be instance of one of the accepted types */ protected boolean shouldAcceptElement(Object obj) { return true; } /** * Creates the specific wizard. * (to be implemented by a subclass) */ abstract protected Wizard createWizard(); protected IStructuredSelection getCurrentSelection() { IWorkbenchWindow window= JavaPlugin.getActiveWorkbenchWindow(); if (window != null) { ISelection selection= window.getSelectionService().getSelection(); if (selection instanceof IStructuredSelection) { return (IStructuredSelection) selection; } } return null; } /** * The user has invoked this action. */ public void run() { if (!fNoChecking && !canActionBeAdded()) { return; } if (!checkWorkspaceNotEmpty()) { return; } Wizard wizard= createWizard(); if (wizard instanceof IWorkbenchWizard) { ((IWorkbenchWizard)wizard).init(getWorkbench(), getCurrentSelection()); } WizardDialog dialog= new WizardDialog(JavaPlugin.getActiveWorkbenchShell(), wizard); PixelConverter converter= new PixelConverter(JavaPlugin.getActiveWorkbenchShell()); dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20)); dialog.create(); dialog.getShell().setText(JavaUIMessages.getString("AbstractOpenWizardAction.title")); //$NON-NLS-1$ dialog.open(); } /** * Tests if the action can be run on the current selection. */ public boolean canActionBeAdded() { IStructuredSelection selection= getCurrentSelection(); if (selection == null || selection.isEmpty()) { return fAcceptEmptySelection; } return isEnabled(selection); } /* * @see IActionDelegate#run(IAction) */ public void run(IAction action) { run(); } /* * @see IWorkbenchWindowActionDelegate#dispose() */ public void dispose() { } /* * @see IWorkbenchWindowActionDelegate#init(IWorkbenchWindow) */ public void init(IWorkbenchWindow window) { } /* * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { // selection taken from selectionprovider } protected boolean checkWorkspaceNotEmpty() { IWorkspace workspace= ResourcesPlugin.getWorkspace(); if (workspace.getRoot().getProjects().length == 0) { Shell shell= JavaPlugin.getActiveWorkbenchShell(); String title= JavaUIMessages.getString("AbstractOpenWizardAction.noproject.title"); String message= JavaUIMessages.getString("AbstractOpenWizardAction.noproject.message"); if (MessageDialog.openQuestion(shell, title, message)) { IWorkbenchWindow window= JavaPlugin.getActiveWorkbenchWindow(); (new NewProjectAction(window)).run(); // using internal class (PR: 6095) return workspace.getRoot().getProjects().length != 0; } return false; } return true; } }
11,442
Bug 11442 Labels of CheckedTreeSelectionDialog aren't localized
The button labels of the CheckedTreeSelectionDialog aren't localized. (See createSelectionButtons()). The class SelectionDialog (which is one of its superclasses) already provides localized labels I think. So you might want to replace the hard coded names with SelectionDialog.SELECT_ALL_TITLE and SelectionDialog.DESELECT_ALL_TITLE (or add your own translation). Even better, because "select all" and "select none" are used quite often, tell the Platform/JFace team to add these to the IDialogConstants interface class.
resolved fixed
ab5b2ac
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T10:26:00Z
2002-03-15T11:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.viewsupport.ContainerCheckedTreeViewer; /** * A class to select elements out of a tree structure. */ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { private CheckboxTreeViewer fViewer; private ILabelProvider fLabelProvider; private ITreeContentProvider fContentProvider; private ISelectionValidator fValidator= null; private ViewerSorter fSorter; private String fEmptyListMessage= JavaUIMessages.getString("ElementTreeSelectionDialog.nothing_available"); //$NON-NLS-1$ private IStatus fCurrStatus= new StatusInfo(); private List fFilters; private Object fInput; private boolean fIsEmpty; private int fWidth= 60; private int fHeight= 18; private boolean fContainerMode; private Object[] fExpandedElements; /** * Constructs an instance of <code>ElementTreeSelectionDialog</code>. * @param labelProvider the label provider to render the entries * @param contentProvider the content provider to evaluate the tree structure */ public CheckedTreeSelectionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider) { super(parent); fLabelProvider= labelProvider; fContentProvider= contentProvider; setResult(new ArrayList(0)); setStatusLineAboveButtons(true); fContainerMode= false; fExpandedElements= null; int shellStyle= getShellStyle(); setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE); } /** * If set, the checked /gray state of containers (inner nodes) is derived from the checked state of its * leaf nodes. * @param containerMode The containerMode to set */ public void setContainerMode(boolean containerMode) { fContainerMode= containerMode; } /** * Sets the initial selection. * Convenience method. * @param selection the initial selection. */ public void setInitialSelection(Object selection) { setInitialSelections(new Object[] {selection}); } /** * Sets the message to be displayed if the list is empty. * @param message the message to be displayed. */ public void setEmptyListMessage(String message) { fEmptyListMessage= message; } /** * Sets the sorter used by the tree viewer. */ public void setSorter(ViewerSorter sorter) { fSorter= sorter; } /** * Adds a filter to the tree viewer. * @param filter a filter. */ public void addFilter(ViewerFilter filter) { if (fFilters == null) fFilters= new ArrayList(4); fFilters.add(filter); } /** * Sets an optional validator to check if the selection is valid. * The validator is invoked whenever the selection changes. * @param validator the validator to validate the selection. */ public void setValidator(ISelectionValidator validator) { fValidator= validator; } /** * Sets the tree input. * @param input the tree input. */ public void setInput(Object input) { fInput= input; } /** * Expands the tree */ public void setExpandedElements(Object[] elements) { fExpandedElements= elements; } /** * Sets the size of the tree in unit of characters. * @param width the width of the tree. * @param height the height of the tree. */ public void setSize(int width, int height) { fWidth= width; fHeight= height; } protected void updateOKStatus() { if (!fIsEmpty) { if (fValidator != null) { fCurrStatus= fValidator.validate(fViewer.getCheckedElements()); updateStatus(fCurrStatus); } else if (!fCurrStatus.isOK()) { fCurrStatus= new StatusInfo(); } } else { fCurrStatus= new StatusInfo(IStatus.ERROR, fEmptyListMessage); } updateStatus(fCurrStatus); } /* * @see Window#open() */ public int open() { fIsEmpty= evaluateIfTreeEmpty(fInput); BusyIndicator.showWhile(null, new Runnable() { public void run() { access$superOpen(); } }); return getReturnCode(); } private void access$superOpen() { super.open(); } /** * Handles cancel button pressed event. */ protected void cancelPressed() { setResult(null); super.cancelPressed(); } /* * @see SelectionStatusDialog#computeResult() */ protected void computeResult() { setResult(Arrays.asList(fViewer.getCheckedElements())); } /* * @see Window#create() */ public void create() { super.create(); List initialSelections= getInitialSelections(); if (initialSelections != null) { fViewer.setCheckedElements(initialSelections.toArray()); } if (fExpandedElements != null) { fViewer.setExpandedElements(fExpandedElements); } updateOKStatus(); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); Label messageLabel= createMessageArea(composite); Control treeWidget= createTreeViewer(composite); Control buttonComposite= createSelectionButtons(composite); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(fWidth); data.heightHint= convertHeightInCharsToPixels(fHeight); treeWidget.setLayoutData(data); if (fIsEmpty) { messageLabel.setEnabled(false); treeWidget.setEnabled(false); buttonComposite.setEnabled(false); } return composite; } private Tree createTreeViewer(Composite parent) { if (fContainerMode) { fViewer= new ContainerCheckedTreeViewer(parent, SWT.BORDER); } else { fViewer= new CheckboxTreeViewer(parent, SWT.BORDER); } fViewer.setContentProvider(fContentProvider); fViewer.setLabelProvider(fLabelProvider); fViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { updateOKStatus(); } }); fViewer.setSorter(fSorter); if (fFilters != null) { for (int i= 0; i != fFilters.size(); i++) fViewer.addFilter((ViewerFilter) fFilters.get(i)); } fViewer.setInput(fInput); return fViewer.getTree(); } /** * Add the selection and deselection buttons to the dialog. * @param composite org.eclipse.swt.widgets.Composite */ private Composite createSelectionButtons(Composite composite) { Composite buttonComposite= new Composite(composite, SWT.RIGHT); GridLayout layout= new GridLayout(); layout.numColumns= 2; buttonComposite.setLayout(layout); GridData data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL); data.grabExcessHorizontalSpace= true; composite.setData(data); Button selectButton= createButton(buttonComposite, IDialogConstants.SELECT_ALL_ID, "Select &All", false); SelectionListener listener= new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fViewer.setCheckedElements(fContentProvider.getElements(fInput)); updateOKStatus(); } }; selectButton.addSelectionListener(listener); Button deselectButton= createButton(buttonComposite, IDialogConstants.DESELECT_ALL_ID, "&Deselect All", false); listener= new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fViewer.setCheckedElements(new Object[0]); updateOKStatus(); } }; deselectButton.addSelectionListener(listener); return buttonComposite; } private boolean evaluateIfTreeEmpty(Object input) { Object[] elements= fContentProvider.getElements(input); if (elements.length > 0) { if (fFilters != null) { for (int i= 0; i < fFilters.size(); i++) { ViewerFilter curr= (ViewerFilter)fFilters.get(i); elements= curr.filter(fViewer, input, elements); } } } return elements.length == 0; } }
12,517
Bug 12517 NPE while renaming refactoring operation while half selected variable name
i highlighted half of the global variable that i have to refactor. it showed an error dialogue box saying "an unexpected error occured". ne help this is the log file - Log: Sat Mar 30 22:01:00 IST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.ASTNodes.getMessages (ASTNodes.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOldE rrorMessages(RenameTempRefactoring.java:222) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze IntroducedCompileErrors(RenameTempRefactoring.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze AST(RenameTempRefactoring.java:193) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkIn put(RenameTempRefactoring.java:175) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:88) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:63) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:755) at org.eclipse.ui.internal.Workbench.run(Workbench.java:738) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396) Log: Sat Mar 30 22:01:56 IST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.ASTNodes.getMessages (ASTNodes.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOldE rrorMessages(RenameTempRefactoring.java:222) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze IntroducedCompileErrors(RenameTempRefactoring.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze AST(RenameTempRefactoring.java:193) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkIn put(RenameTempRefactoring.java:175) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:88) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:63) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:755) at org.eclipse.ui.internal.Workbench.run(Workbench.java:738) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396) Log: Sat Mar 30 22:02:12 IST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.ASTNodes.getMessages (ASTNodes.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOldE rrorMessages(RenameTempRefactoring.java:222) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze IntroducedCompileErrors(RenameTempRefactoring.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze AST(RenameTempRefactoring.java:193) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkIn put(RenameTempRefactoring.java:175) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:88) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:63) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:755) at org.eclipse.ui.internal.Workbench.run(Workbench.java:738) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
resolved fixed
73a4fe0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T10:38:34Z
2002-03-30T17:40:00Z
org.eclipse.jdt.ui/core
12,517
Bug 12517 NPE while renaming refactoring operation while half selected variable name
i highlighted half of the global variable that i have to refactor. it showed an error dialogue box saying "an unexpected error occured". ne help this is the log file - Log: Sat Mar 30 22:01:00 IST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.ASTNodes.getMessages (ASTNodes.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOldE rrorMessages(RenameTempRefactoring.java:222) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze IntroducedCompileErrors(RenameTempRefactoring.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze AST(RenameTempRefactoring.java:193) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkIn put(RenameTempRefactoring.java:175) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:88) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:63) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:755) at org.eclipse.ui.internal.Workbench.run(Workbench.java:738) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396) Log: Sat Mar 30 22:01:56 IST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.ASTNodes.getMessages (ASTNodes.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOldE rrorMessages(RenameTempRefactoring.java:222) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze IntroducedCompileErrors(RenameTempRefactoring.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze AST(RenameTempRefactoring.java:193) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkIn put(RenameTempRefactoring.java:175) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:88) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:63) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:755) at org.eclipse.ui.internal.Workbench.run(Workbench.java:738) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396) Log: Sat Mar 30 22:02:12 IST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.ASTNodes.getMessages (ASTNodes.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOldE rrorMessages(RenameTempRefactoring.java:222) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze IntroducedCompileErrors(RenameTempRefactoring.java:209) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyze AST(RenameTempRefactoring.java:193) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkIn put(RenameTempRefactoring.java:175) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:88) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:63) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:755) at org.eclipse.ui.internal.Workbench.run(Workbench.java:738) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
resolved fixed
73a4fe0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T10:38:34Z
2002-03-30T17:40:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java
10,158
Bug 10158 [hovering] Report protection in hover-help
1. Hover the mouse over a method call in the JavaEditor 2. When the hover-help pops up note that it contains the method signature and JavaDoc, but not the method's protection The protection information is also useful to potential callers of that method and should be reported with the signature.
resolved fixed
37d8aaa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T11:16:29Z
2002-02-25T15:13:20Z
org.eclipse.jdt.ui/core
10,158
Bug 10158 [hovering] Report protection in hover-help
1. Hover the mouse over a method call in the JavaEditor 2. When the hover-help pops up note that it contains the method signature and JavaDoc, but not the method's protection The protection information is also useful to potential callers of that method and should be reported with the signature.
resolved fixed
37d8aaa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T11:16:29Z
2002-02-25T15:13:20Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java
10,158
Bug 10158 [hovering] Report protection in hover-help
1. Hover the mouse over a method call in the JavaEditor 2. When the hover-help pops up note that it contains the method signature and JavaDoc, but not the method's protection The protection information is also useful to potential callers of that method and should be reported with the signature.
resolved fixed
37d8aaa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T11:16:29Z
2002-02-25T15:13:20Z
org.eclipse.jdt.ui/core
10,158
Bug 10158 [hovering] Report protection in hover-help
1. Hover the mouse over a method call in the JavaEditor 2. When the hover-help pops up note that it contains the method signature and JavaDoc, but not the method's protection The protection information is also useful to potential callers of that method and should be reported with the signature.
resolved fixed
37d8aaa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T11:16:29Z
2002-02-25T15:13:20Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
10,158
Bug 10158 [hovering] Report protection in hover-help
1. Hover the mouse over a method call in the JavaEditor 2. When the hover-help pops up note that it contains the method signature and JavaDoc, but not the method's protection The protection information is also useful to potential callers of that method and should be reported with the signature.
resolved fixed
37d8aaa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T11:16:29Z
2002-02-25T15:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditorMessages.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.javaeditor; import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; public class JavaEditorMessages { private static final String RESOURCE_BUNDLE= "org.eclipse.jdt.internal.ui.javaeditor.JavaEditorMessages";//$NON-NLS-1$ private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); private JavaEditorMessages() { } public static String getString(String key) { try { return fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } public static ResourceBundle getResourceBundle() { return fgResourceBundle; } /** * Gets a string from the resource bundle and formats it with arguments */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } }
10,158
Bug 10158 [hovering] Report protection in hover-help
1. Hover the mouse over a method call in the JavaEditor 2. When the hover-help pops up note that it contains the method signature and JavaDoc, but not the method's protection The protection information is also useful to potential callers of that method and should be reported with the signature.
resolved fixed
37d8aaa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T11:16:29Z
2002-02-25T15:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/OrganizeImportsAction.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery; import org.eclipse.jdt.internal.corext.util.TypeInfo; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider; public class OrganizeImportsAction extends Action { private ITextEditor fEditor; public OrganizeImportsAction() { this(null); } public OrganizeImportsAction(ITextEditor editor) { super(JavaEditorMessages.getString("OrganizeImportsAction.label")); //$NON-NLS-1$ setToolTipText(JavaEditorMessages.getString("OrganizeImportsAction.tooltip")); //$NON-NLS-1$ setDescription(JavaEditorMessages.getString("OrganizeImportsAction.description")); //$NON-NLS-1$ setContentEditor(editor); WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION); } public static boolean canActionBeAdded(ISelection selection) { if (selection instanceof IStructuredSelection && !selection.isEmpty()) { List elements= ((IStructuredSelection)selection).toList(); if (elements.size() == 1) { return (elements.get(0) instanceof IImportContainer); } } return false; } /** * @see IAction#actionPerformed */ public void run() { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput()); if (cu != null) { String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); boolean ignoreLowerCaseNames= ImportOrganizePreferencePage.doIgnoreLowerCaseNames(); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, false, createChooseImportQuery()); try { BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext(); context.run(false, true, new WorkbenchRunnableAdapter(op)); } catch (InvocationTargetException e) { JavaPlugin.log(e); MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), JavaEditorMessages.getString("OrganizeImportsAction.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$ } catch (InterruptedException e) { IProblem problem= op.getParsingError(); if (problem != null) { showParsingErrorDialog(problem); int start= problem.getSourceStart(); int end= problem.getSourceEnd(); if (start != -1 && end != -1) { fEditor.selectAndReveal(start, end - start); } } } } else { JavaPlugin.logErrorMessage("OrganizeImportsAction.run: Working copy is null"); } } private IChooseImportQuery createChooseImportQuery() { return new IChooseImportQuery() { public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) { return doChooseImports(openChoices, ranges); } }; } private TypeInfo[] doChooseImports(TypeInfo[][] openChoices, final ISourceRange[] ranges) { // remember selection ISelection sel= fEditor.getSelectionProvider().getSelection(); TypeInfo[] result= null;; ILabelProvider labelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED); MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(JavaPlugin.getActiveWorkbenchShell(), labelProvider) { protected void handleSelectionChanged() { super.handleSelectionChanged(); // show choices in editor doListSelectionChanged(getCurrentPage(), ranges); } }; dialog.setTitle(JavaEditorMessages.getString("OrganizeImportsAction.selectiondialog.title")); //$NON-NLS-1$ dialog.setMessage(JavaEditorMessages.getString("OrganizeImportsAction.selectiondialog.message")); //$NON-NLS-1$ dialog.setElements(openChoices); if (dialog.open() == dialog.OK) { Object[] res= dialog.getResult(); result= new TypeInfo[res.length]; for (int i= 0; i < res.length; i++) { Object[] array= (Object[]) res[i]; if (array.length > 0) result[i]= (TypeInfo) array[0]; } } // restore selection if (sel instanceof ITextSelection) { ITextSelection textSelection= (ITextSelection) sel; fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength()); } return result; } private void doListSelectionChanged(int page, ISourceRange[] ranges) { if (page >= 0 && page < ranges.length) { ISourceRange range= ranges[page]; fEditor.selectAndReveal(range.getOffset(), range.getLength()); } } public void setContentEditor(ITextEditor editor) { fEditor= editor; setEnabled(editor != null && fEditor.isEditable()); } private void showParsingErrorDialog(IProblem problem) { String title= JavaEditorMessages.getString("OrganizeImportsAction.error.title"); String[] args= { String.valueOf(problem.getSourceLineNumber()), problem.getMessage() }; String message= JavaEditorMessages.getFormattedString("OrganizeImportsAction.error.parsing.message", args); MessageDialog.openInformation(JavaPlugin.getActiveWorkbenchShell(), title, message); } }
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
org.eclipse.jdt.ui/core
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
org.eclipse.jdt.ui/core
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/GetterSetterUtil.java
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
org.eclipse.jdt.ui/core
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/NameProposer.java
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
org.eclipse.jdt.ui/core
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameFieldRefactoring.java
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
org.eclipse.jdt.ui/ui
6,887
Bug 6887 Create Getter and Setter should create isFoo for booleans
Create getter and setter should create an 'is' method for booleans not a 'get' method.
resolved fixed
bf3af7b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T13:52:45Z
2001-12-13T10:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameFieldInputWizardPage.java
12,596
Bug 12596 exception on saving dirty editors
20020328 Log: Tue Apr 02 14:42:49 GMT+02:00 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.RangeCheck(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction$1.run (ReorgDestinationAction.java:199) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run (ProgressMonitorDialog.java:335) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.ensureSaved (ReorgDestinationAction.java:168) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.run (ReorgDestinationAction.java:80) at org.eclipse.jdt.internal.ui.reorg.JdtCopyAction.run (JdtCopyAction.java:58) at org.eclipse.jdt.internal.ui.reorg.PasteResourcesFromClipboardAction.pasteResourc es(PasteResourcesFromClipboardAction.java:60) at org.eclipse.jdt.internal.ui.reorg.PasteResourcesFromClipboardAction.run (PasteResourcesFromClipboardAction.java:53) at org.eclipse.jdt.internal.ui.reorg.DualReorgAction.run (DualReorgAction.java:49) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:738) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
resolved fixed
a7cff8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T14:10:42Z
2002-04-02T12:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/ReorgDestinationAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.reorg; import java.lang.reflect.InvocationTargetException; 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.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.dialogs.ListSelectionDialog; import org.eclipse.jdt.core.IJavaElement; 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.ui.JavaElementContentProvider; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.internal.corext.refactoring.Assert; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.StructuredSelectionProvider; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.PackageFilter; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.viewsupport.ListContentProvider; abstract class ReorgDestinationAction extends ReorgAction { public ReorgDestinationAction(String name, ISelectionProvider provider) { super(name, provider); } public ReorgDestinationAction(String name, StructuredSelectionProvider provider) { super(name, provider); } /* * @see Action#run() */ public void run() { List elements= getStructuredSelection().toList(); if (!ensureSaved(elements, getActionName())) return; ReorgRefactoring refactoring= createRefactoring(elements); setUnsavedFileList(refactoring, elements); Object destination= selectDestination(refactoring); if (destination == null) return; try{ String duplicate= getDuplicatedElementName(elements); if (duplicate != null){ String message= "Two or more elements named " + duplicate + " are selected."; MessageDialog.openInformation(JavaPlugin.getActiveWorkbenchShell().getShell(), "Duplicate Element Name", message); return; } refactoring.setDestination(destination); Set excluded= getExcluded(refactoring); if (excluded == null) //canceled return; if (excluded.size() == elements.size()) return; refactoring.setExcludedElements(excluded); if (! isOkToProceed(refactoring)) return; doReorg(refactoring); } catch (JavaModelException e){ ExceptionHandler.handle(e, "Exception", "Unexpected exception occurred. See log for details."); } } /** * returns null if no 2 elements have the same name */ private static String getDuplicatedElementName(List elements){ String[] names= getElementNames(elements); if (names.length == 0) return null; Arrays.sort(names); String last= names[0]; for (int i= 1; i < names.length; i++){ //non standard loop if (last.equals(names[i])) return last; last= names[i]; } return null; } abstract String getActionName(); abstract String getDestinationDialogMessage(); abstract ReorgRefactoring createRefactoring(List elements); //hook to override //returns null iff canceled Set getExcluded(ReorgRefactoring refactoring) throws JavaModelException{ return new HashSet(0); } //hook to override protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{ return true; } void doReorg(ReorgRefactoring refactoring) throws JavaModelException{ MultiStatus status= perform(refactoring); if (status.isOK()) return; JavaPlugin.log(status); ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), getActionName(), "An error occurred while reorganizing resources", status); } private static boolean ensureSaved(List elements, String actionName) { List unsavedEditors= new ArrayList(); List unsavedElements= new ArrayList(); collectUnsavedEditors(elements, unsavedEditors, unsavedElements); if (unsavedEditors.isEmpty()) return true; ListSelectionDialog dialog = createUnsavedEditorDialog(unsavedElements); if (dialog.open() != dialog.OK) return false; IRunnableWithProgress r= createSaveEditorOperation(dialog.getResult(), elements, unsavedEditors); try { new ProgressMonitorDialog(JavaPlugin.getActiveWorkbenchShell()).run(false, false, r); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, actionName, ReorgMessages.getString("ReorgAction.exception.saving")); //$NON-NLS-1$ return false; } catch (InterruptedException e) { } return true; } private static void setUnsavedFileList(ReorgRefactoring refactoring, List elements){ List unsavedEditors= new ArrayList(0); collectUnsavedEditors(elements, unsavedEditors, new ArrayList(0)); refactoring.setUnsavedFiles(getFiles(unsavedEditors)); } private static IFile[] getFiles(List editorParts){ List result= new ArrayList(editorParts.size()); for (Iterator iter= editorParts.iterator(); iter.hasNext(); ){ IEditorPart each= (IEditorPart)iter.next(); IEditorInput input= each.getEditorInput(); if (input instanceof IFileEditorInput) result.add(((IFileEditorInput)input).getFile()); } return (IFile[]) result.toArray(new IFile[result.size()]); } private static IRunnableWithProgress createSaveEditorOperation(final Object[] elementsToSave, final List elements, final List unsavedEditors) { return new IRunnableWithProgress() { public void run(IProgressMonitor pm) { pm.beginTask(ReorgMessages.getString("ReorgAction.task.saving"), elementsToSave.length); //$NON-NLS-1$ for (int i= 0; i < elementsToSave.length; i++) { IEditorPart editor= (IEditorPart)unsavedEditors.get(elements.indexOf(elementsToSave[i])); editor.doSave(new SubProgressMonitor(pm, 1)); } pm.done(); } }; } private static ListSelectionDialog createUnsavedEditorDialog(List unsavedElements) { int labelFlags= JavaElementLabelProvider.SHOW_DEFAULT | JavaElementLabelProvider.SHOW_POST_QUALIFIED; Shell parent= JavaPlugin.getActiveWorkbenchShell(); String msg= ReorgMessages.getString("ReorgAction.checkSaveTargets"); //$NON-NLS-1$ ListSelectionDialog dialog= new ListSelectionDialog(parent, unsavedElements, new ListContentProvider(), new JavaElementLabelProvider(labelFlags), msg); dialog.setInitialSelections(unsavedElements.toArray()); return dialog; } private static void collectUnsavedEditors(List elements, List unsavedEditors, List unsavedElements) { IEditorPart[] editors= JavaPlugin.getDirtyEditors(); for (int i= 0; i < editors.length; i++) { for (Iterator iter= elements.iterator(); iter.hasNext(); ){ Object element= iter.next(); if (EditorUtility.isEditorInput(element, editors[i])) { unsavedEditors.add(editors[i]); unsavedElements.add(element); } } } } private static String[] getElementNames(List elements){ String[] result= new String[elements.size()]; int i= 0; for (Iterator iter= elements.iterator(); iter.hasNext(); ){ result[i]= ReorgUtils.getName(iter.next()); i++; } return result; } //overriden by d'n'd - must be protected protected Object selectDestination(ReorgRefactoring refactoring) { JavaElementContentProvider cp= new JavaElementContentProvider() { public boolean hasChildren(Object element) { // prevent the + from being shown in front of packages return !(element instanceof IPackageFragment) && super.hasChildren(element); } }; ElementTreeSelectionDialog dialog= createDestinationSelectionDialog(JavaPlugin.getActiveWorkbenchShell(), new DestinationRenderer(JavaElementLabelProvider.SHOW_SMALL_ICONS ), cp, refactoring); dialog.setTitle(getActionName()); dialog.setValidator(new ReorgSelectionValidator(refactoring)); dialog.addFilter(new ContainerFilter(refactoring)); dialog.setSorter(new JavaElementSorter()); dialog.setMessage(getDestinationDialogMessage()); dialog.setSize(60, 18); dialog.setInput(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot())); dialog.setInitialSelection(computeCommonParent(refactoring.getElementsToReorg())); if (dialog.open() != dialog.CANCEL) return dialog.getFirstResult(); return null; } ElementTreeSelectionDialog createDestinationSelectionDialog(Shell parent, ILabelProvider labelProvider, JavaElementContentProvider cp, ReorgRefactoring refactoring){ return new ElementTreeSelectionDialog(parent, labelProvider, cp); } private static Object computeCommonParent(List elements){ if (elements.isEmpty()) return null; Object parent= elements.get(0); for (Iterator iter= elements.iterator(); iter.hasNext(); ){ parent= computeCommonParent(parent, iter.next()); } IResource parentRes= getResource(parent); IJavaElement parentElement= JavaCore.create(parentRes); if (parentElement != null) return parentElement; return getResource(parent); } private static Object computeCommonParent(Object e1, Object e2){ IResource r1= getResource(e1); IResource r2= getResource(e2); if (r1 == null && r2 == null) return null; if (r1 == null) return r2.getParent(); if (r2 == null) return r1.getParent(); if (r1.equals(r2)) return r1.getParent(); if (r1.getFullPath().isPrefixOf(r2.getFullPath())) return r1; if (r2.getFullPath().isPrefixOf(r1.getFullPath())) return r2; IPath p1= r1.getParent().getFullPath(); IPath p2= r2.getParent().getFullPath(); IPath commonPath= new Path(""); int segCount= Math.min(p1.segmentCount(), p2.segmentCount()); for (int i= 0; i < segCount; i++){ if (p1.segment(i).equals(p2.segment(i))) commonPath= commonPath.append(p1.segment(i)); else break; } return ResourcesPlugin.getWorkspace().getRoot().findMember(commonPath); } private static IResource getResource(Object o) { try{ if (o instanceof IResource) return (IResource)o; else if (o instanceof IJavaElement) return ((IJavaElement)o).getCorrespondingResource(); else return null; } catch (JavaModelException e){ JavaPlugin.log(e); return null; } } /* non java-doc * @see IRefactoringAction#canOperateOn(IStructuredSelection) */ public boolean canOperateOn(IStructuredSelection selection) { return canActivate(createRefactoring(selection.toList())); } //----- private static class ContainerFilter extends PackageFilter { private ReorgRefactoring fRefactoring; ContainerFilter(ReorgRefactoring refactoring) { Assert.isNotNull(refactoring); fRefactoring= refactoring; } public boolean select(Viewer viewer, Object parent, Object o) { if (fRefactoring.getElementsToReorg().contains(o)) return false; return fRefactoring.canBeAncestor(o); } } //----- private static class DestinationRenderer extends JavaElementLabelProvider { public DestinationRenderer(int flags) { super(flags); } public String getText(Object element) { try { if (element instanceof IPackageFragmentRoot) { IPackageFragmentRoot root= (IPackageFragmentRoot)element; if (root.getUnderlyingResource() instanceof IProject) return ReorgMessages.getString("DestinationRenderer.packages"); //$NON-NLS-1$ } } catch (JavaModelException e) { ExceptionHandler.handle(e, "Exception", "Unexpected exception occurred. See log for details."); } return super.getText(element); } } //------ private static class ReorgSelectionValidator implements ISelectionValidator { private ReorgRefactoring fRefactoring; public ReorgSelectionValidator(ReorgRefactoring refactoring) { Assert.isNotNull(refactoring); fRefactoring= refactoring; } public IStatus validate(Object[] selection) { if (selection.length != 1) return new StatusInfo(IStatus.ERROR, ""); try{ if (fRefactoring.isValidDestination(selection[0])) return new StatusInfo(); return new StatusInfo(IStatus.ERROR, ""); } catch (JavaModelException e){ ExceptionHandler.handle(e, "Exception", "Unexpected exception occurred. See log for details."); return new StatusInfo(IStatus.ERROR, ""); } } } }
10,758
Bug 10758 utilize classpath variable initializers
From JCORE: "the CLASSPATH VARIABLE INITIALIZE should be leveraged by the orgg.eclipse.jdt.launching plugin to initialize JRELIB, JRESRC etc." CLASSPATH VARIABLE INITIALIZER============================== Added extension point to jdtcore so as to allow client plugins to register classpath variable initializers. Extension point is "org.eclipse.jdt.core.classpathVariableInitializer"). (also check development resources for design notes on this topic) Note that each classpath variable, if unbound, will trigger its registered initializer exactly once per session. If unsuccessful, it will stay unbound.
verified fixed
c544852
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-02T22:59:09Z
2002-03-05T14:53:20Z
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.IWorkspaceRunnable; 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.IProgressMonitor; 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.resource.ImageRegistry; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; 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.launching.JavaRuntime; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPreferencePage; import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider; import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart; import org.eclipse.jdt.internal.ui.preferences.AppearancePreferencePage; import org.eclipse.jdt.internal.ui.preferences.ClasspathVariablesPreferencePage; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage; import org.eclipse.jdt.internal.ui.preferences.CompilerPreferencePage; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaBuilderPreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage; import org.eclipse.jdt.internal.ui.preferences.RefactoringPreferencePage; import org.eclipse.jdt.internal.ui.preferences.TemplatePreferencePage; import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage; 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 { private static JavaPlugin fgJavaPlugin; /* * XXX: Work in progress. Might be moved to Java UI. */ public static String ID_BROWSING_PERSPECTIVE= JavaUI.ID_PLUGIN + ".JavaBrowsingPerspective"; public static String ID_PROJECTS_VIEW= JavaUI.ID_PLUGIN + ".ProjectsView"; public static String ID_PACKAGES_VIEW= JavaUI.ID_PLUGIN + ".PackagesView"; public static String ID_TYPES_VIEW= JavaUI.ID_PLUGIN + ".TypesView"; public static String ID_MEMBERS_VIEW= JavaUI.ID_PLUGIN + ".MembersView"; private CompilationUnitDocumentProvider fCompilationUnitDocumentProvider; private ClassFileDocumentProvider fClassFileDocumentProvider; private JavaTextTools fJavaTextTools; private ProblemMarkerManager fProblemMarkerManager; private ImageDescriptorRegistry fImageDescriptorRegistry; 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(7); 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].getEditors(); for (int z= 0; z < editors.length; z++) { IEditorPart editor= editors[z]; IEditorInput input= editor.getEditorInput(); if (editor.isDirty() && !inputs.contains(input)) { inputs.add(input); 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(), JavaStatusConstants.INTERNAL_ERROR, message, null)); } public static void logErrorStatus(String message, IStatus status) { if (status == null) { logErrorMessage(message); return; } MultiStatus multi= new MultiStatus(getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, null); multi.add(status); log(multi); } public static void log(Throwable e) { log(new Status(IStatus.ERROR, getPluginId(), JavaStatusConstants.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() { IAdapterManager manager= Platform.getAdapterManager(); manager.registerAdapters(new JavaElementAdapterFactory(), IJavaElement.class); manager.registerAdapters(new MarkerAdapterFactory(), IMarker.class); manager.registerAdapters(new EditorInputAdapterFactory(), IEditorInput.class); manager.registerAdapters(new ResourceAdapterFactory(), IResource.class); IWorkspaceRunnable runnable= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { JavaRuntime.initializeJREVariables(monitor); } }; try { getWorkspace().run(runnable, null); } catch (CoreException e) { log(e); } try { JavaDocLocations.loadJavadocLocations(); } catch (CoreException e) { log(e); } } /* (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(); super.shutdown(); if (fCompilationUnitDocumentProvider != null) { fCompilationUnitDocumentProvider.shutdown(); fCompilationUnitDocumentProvider= null; } if (fJavaTextTools != null) { fJavaTextTools.dispose(); fJavaTextTools= null; } JavaDocLocations.saveJavadocLocations(); } private IWorkbenchPage internalGetActivePage() { IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow(); if (window == null) return null; return getWorkbench().getActiveWorkbenchWindow().getActivePage(); } public CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() { if (fCompilationUnitDocumentProvider == null) fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider(); return fCompilationUnitDocumentProvider; } public ClassFileDocumentProvider getClassFileDocumentProvider() { if (fClassFileDocumentProvider == null) fClassFileDocumentProvider= new ClassFileDocumentProvider(); return fClassFileDocumentProvider; } public IWorkingCopyManager getWorkingCopyManager() { return getCompilationUnitDocumentProvider(); } public ProblemMarkerManager getProblemMarkerManager() { if (fProblemMarkerManager == null) fProblemMarkerManager= new ProblemMarkerManager(); return fProblemMarkerManager; } public JavaTextTools getJavaTextTools() { if (fJavaTextTools == null) fJavaTextTools= new JavaTextTools(getPreferenceStore()); return fJavaTextTools; } /** * 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 GroupMarker(IContextMenuConstants.GROUP_OPEN)); menu.add(new Separator(IContextMenuConstants.GROUP_SHOW)); menu.add(new Separator(IContextMenuConstants.GROUP_BUILD)); menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE)); menu.add(new GroupMarker(IContextMenuConstants.GROUP_GENERATE)); menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH)); 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); store.setDefault(IPreferencesConstants.EDITOR_SHOW_HOVER, true); store.setDefault(IPreferencesConstants.EDITOR_SHOW_SEGMENTS, false); JavaBasePreferencePage.initDefaults(store); AppearancePreferencePage.initDefaults(store); ImportOrganizePreferencePage.initDefaults(store); ClasspathVariablesPreferencePage.initDefaults(store); RefactoringPreferencePage.initDefaults(store); CodeFormatterPreferencePage.initDefaults(store); CompilerPreferencePage.initDefaults(store); PackageExplorerPart.initDefaults(store); JavaEditorPreferencePage.initDefaults(store); TemplatePreferencePage.initDefaults(store); CodeGenerationPreferencePage.initDefaults(store); JavadocPreferencePage.initDefaults(store); JavaBuilderPreferencePage.initDefaults(store); WorkInProgressPreferencePage.initDefaults(store); JavaBrowsingPreferencePage.initDefaults(store); } private ImageDescriptorRegistry internalGetImageDescriptorRegistry() { if (fImageDescriptorRegistry == null) fImageDescriptorRegistry= new ImageDescriptorRegistry(); return fImageDescriptorRegistry; } }
12,449
Bug 12449 delete action in type hierarchy is not registered on 'del' key
TypeHierarchyViewPart should call ReorgGroup.createDeleteAction see PackageExplorerViewPart
resolved fixed
ffeee18
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-04T09:07:33Z
2002-03-28T15: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.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; 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.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.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.IInputSelectionProvider; 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.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.PageBook; 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.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; 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.ContextMenuGroup; import org.eclipse.jdt.internal.ui.dnd.BasicSelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.BuildGroup; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; 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 { 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$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of inut elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private IProblemChangedListener fHierarchyProblemListener; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private MethodsViewer fMethodsViewer; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private boolean fIsEnableMemberFilter; 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 IDialogSettings fDialogSettings; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private int fCurrentOrientation; private EnableMemberFilterAction fEnableMemberFilterAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private IPartListener fPartListener; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fHierarchyProblemListener= null; 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); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); 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) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; } /** * 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) { ICompilationUnit cu= member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { member= (IMember) cu.getOriginal(member); if (member == null) { return; } } if (member.getElementType() != IJavaElement.TYPE) { Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { methodControl.setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } else { Control viewerControl= getCurrentViewer().getControl(); if (viewerControl != null && !viewerControl.isDisposed()) { viewerControl.setFocus(); } 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) { 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")); return; } } if (element.getElementType() == IJavaElement.METHOD || element.getElementType() == IJavaElement.FIELD || element.getElementType() == IJavaElement.INITIALIZER) { element= ((IMember) element).getDeclaringType(); } } } 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; fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e); clearInput(); return; } fPagebook.showPage(fTypeMethodsSplitter); if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } IType root= getSelectableType(fInputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); } } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); getSite().getPage().removePartListener(fPartListener); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } if (fMethodsViewer != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fMethodsViewer); } super.dispose(); } 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.F4) { OpenTypeHierarchyUtil.open(getSite().getSelectionProvider().getSelection(), getSite().getWorkbenchWindow()); return; } else if (event.keyCode == SWT.F5) { updateHierarchyViewer(); 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); } 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()); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fMethodsViewer); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_COPY; DragSource source= new DragSource(fMethodsViewer.getControl(), ops); source.setTransfer(transfers); source.addDragListener(new BasicSelectionTransferDragAdapter(fMethodsViewer)); for (int i= 0; i < fAllViewers.length; i++) { TypeHierarchyViewer curr= fAllViewers[i]; curr.addDropSupport(ops, transfers, new TypeHierarchyTransferDropAdapter(this, curr)); } } 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); initDragAndDrop(); 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); // 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)); // 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); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, ReorgGroup.createDeleteAction(fSelectionProviderMediator)); IJavaElement input= determineInputElement(); if (fMemento != null) { restoreState(fMemento, input); } else if (input != null) { setInputElement(input); } else { setViewerVisibility(false); } ReorgGroup.addGlobalReorgActions(getViewSite().getActionBars(), getViewSite().getSelectionProvider()); WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); } /** * 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); // viewer entries viewer.contributeToContextMenu(menu); IStructuredSelection selection= (IStructuredSelection)viewer.getSelection(); if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { addOpenPerspectiveItem(menu, selection); } addOpenWithMenu(menu, selection); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnTypeAction); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnSelectionAction); addRefactoring(menu, viewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, viewer); } /** * 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); } //menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer)); addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection()); addRefactoring(menu, fMethodsViewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, fMethodsViewer); } private void addRefactoring(IMenuManager menu, IInputSelectionProvider viewer){ MenuManager refactoring= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.refactor")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, viewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IJavaElement)) return; IResource resource= null; try { resource= ((IJavaElement)element).getUnderlyingResource(); } catch(JavaModelException e) { // ignore } if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } private void addOpenPerspectiveItem(IMenuManager menu, IStructuredSelection selection) { OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, selection); } /** * 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) { ISelection sel= null; if (elem.getElementType() != IJavaElement.TYPE) { return (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); } private void internalSelectMember(IMember member) { fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener); fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY); fMethodsViewer.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() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); // 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(IType input) { if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } fMethodsViewer.setInput(input); } } private void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); } else { typeSelectionChanged(e.getSelection()); } } private void methodSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (fIsEnableMemberFilter) { IMember[] memberFilter= null; if (nSelected > 0) { memberFilter= new IMember[nSelected]; selected.toArray(memberFilter); } setMemberFilter(memberFilter); updateHierarchyViewer(); 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)) { try { getSite().getPage().removePartListener(fPartListener); EditorUtility.openInEditor(elem, false); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } catch (CoreException e) { JavaPlugin.log(e); } } } 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(); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { internalSelectType(getSelectableType(fInputElement), false); currSelection= getCurrentViewer().getSelection(); } if (!fIsEnableMemberFilter) { typeSelectionChanged(currSelection); } } updateTitle(); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } fHierarchyProblemListener= getCurrentViewer(); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fHierarchyProblemListener); 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(); 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 ITypeHierarchyLifeCycleListener. * Can be called from any thread */ private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { doTypeHierarchyChangedOnViewers(changedTypes); } }); } } private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } updateHierarchyViewer(); } else { // elements in hierarchy modified if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } fMethodsViewer.refresh(); } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { return (IJavaElement) input; } 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) { memento.putString(TAG_INPUT, fInputElement.getHandleIdentifier()); } 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); } /** * 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.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); if (selectionId != null) { IJavaElement elem= JavaCore.create(selectionId); if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) { internalSelectType((IMember)elem, false); } } fMethodsViewer.restoreState(memento); } /** * Link selection to active editor. */ private void editorActivated(IEditorPart editor) { if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) { 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.getStatus()); } } }
12,590
Bug 12590 Returning the type when local var is selected breaks refactoring
There seems to be a code resolve change: it returns the type if a local var is selected. This breaks refactoring: before I could select a local var and then rename it but now I get a "Rename Type" wizard. It is no longer possible to rename a local variable.
resolved fixed
20a37b8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-04T11:43:36Z
2002-04-02T09:33:20Z
org.eclipse.jdt.ui/ui
12,590
Bug 12590 Returning the type when local var is selected breaks refactoring
There seems to be a code resolve change: it returns the type if a local var is selected. This breaks refactoring: before I could select a local var and then rename it but now I get a "Rename Type" wizard. It is no longer possible to rename a local variable.
resolved fixed
20a37b8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-04T11:43:36Z
2002-04-02T09:33:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RenameActionDelegate.java
12,590
Bug 12590 Returning the type when local var is selected breaks refactoring
There seems to be a code resolve change: it returns the type if a local var is selected. This breaks refactoring: before I could select a local var and then rename it but now I get a "Rename Type" wizard. It is no longer possible to rename a local variable.
resolved fixed
20a37b8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-04T11:43:36Z
2002-04-02T09:33:20Z
org.eclipse.jdt.ui/ui
12,590
Bug 12590 Returning the type when local var is selected breaks refactoring
There seems to be a code resolve change: it returns the type if a local var is selected. This breaks refactoring: before I could select a local var and then rename it but now I get a "Rename Type" wizard. It is no longer possible to rename a local variable.
resolved fixed
20a37b8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-04T11:43:36Z
2002-04-02T09:33:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RenameTempAction.java
12,861
Bug 12861 Replace from local history does not always preserve line delimiters.
If a history file contains the two line delimiters '\r\n\r' the second '\r' is not preserved.
resolved fixed
ad1b0fa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-05T12:45:14Z
2002-04-05T12:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaAddElementFromHistory.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.util.ResourceBundle; import java.lang.reflect.InvocationTargetException; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.*; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.IEditorInput; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.corext.codemanipulation.MemberEdit; import org.eclipse.jdt.internal.corext.textmanipulation.*; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.compare.JavaHistoryAction.JavaTextBufferNode; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.compare.*; public class JavaAddElementFromHistory extends JavaHistoryAction { private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.AddFromHistoryAction"; //$NON-NLS-1$ private JavaEditor fEditor; public JavaAddElementFromHistory() { } public void run(IAction action) { String errorTitle= CompareMessages.getString("AddFromHistory.title"); //$NON-NLS-1$ String errorMessage= CompareMessages.getString("AddFromHistory.internalErrorMessage"); //$NON-NLS-1$ Shell shell= JavaPlugin.getActiveWorkbenchShell(); // shell can be null; as a result error dialogs won't be parented ICompilationUnit cu= null; IParent parent= null; IMember input= null; // analyse selection ISelection selection= getSelection(); if (selection.isEmpty()) { // no selection: we try to use the editor's input if (fEditor != null) { IEditorInput editorInput= fEditor.getEditorInput(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); if (manager != null) { cu= manager.getWorkingCopy(editorInput); parent= cu; } } } else { input= getEditionElement(selection); if (input != null) { cu= input.getCompilationUnit(); if (input instanceof IParent) { parent= (IParent)input; input= null; } else { IJavaElement parentElement= input.getParent(); if (parentElement instanceof IParent) parent= (IParent)parentElement; } } else { if (selection instanceof IStructuredSelection) { Object o= ((IStructuredSelection)selection).getFirstElement(); if (o instanceof ICompilationUnit) { cu= (ICompilationUnit) o; parent= cu; } } } } if (parent == null || cu == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } IFile file= getFile(parent); if (file == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } boolean inEditor= beingEdited(file); if (inEditor) { parent= (IParent) getWorkingCopy((IJavaElement)parent); if (input != null) input= (IMember) getWorkingCopy(input); } // get a TextBuffer where to insert the text TextBuffer buffer= null; try { buffer= TextBuffer.acquire(file); // configure EditionSelectionDialog and let user select an edition ITypedElement target= new JavaTextBufferNode(buffer, inEditor); ITypedElement[] editions= buildEditions(target, file); ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME); EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle); d.setAddMode(true); ITypedElement ti= d.selectEdition(target, editions, parent); if (!(ti instanceof IStreamContentAccessor)) return; // user cancel // from the edition get the lines (text) to insert String[] lines= null; try { lines= JavaCompareUtilities.readLines(((IStreamContentAccessor) ti).getContents()); } catch (CoreException ex) { JavaPlugin.log(ex); } if (lines == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } // build the TextEdit that inserts the text into the buffer TextEdit edit= null; if (input != null) edit= new MemberEdit(input, MemberEdit.INSERT_AFTER, lines, CodeFormatterPreferencePage.getTabSize()); else edit= createEdit(lines, parent); if (edit == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } IProgressMonitor nullProgressMonitor= new NullProgressMonitor(); TextBufferEditor editor= new TextBufferEditor(buffer); editor.add(edit); editor.performEdits(nullProgressMonitor); final TextBuffer bb= buffer; IRunnableWithProgress r= new IRunnableWithProgress() { public void run(IProgressMonitor pm) throws InvocationTargetException { try { TextBuffer.commitChanges(bb, false, pm); } catch (CoreException ex) { throw new InvocationTargetException(ex); } } }; if (inEditor) { // we don't show progress r.run(nullProgressMonitor); } else { ProgressMonitorDialog pd= new ProgressMonitorDialog(shell); pd.run(true, false, r); } } catch(InvocationTargetException ex) { JavaPlugin.log(ex); MessageDialog.openError(shell, errorTitle, errorMessage); } catch(InterruptedException ex) { // shouldn't be called because is not cancable } catch(CoreException ex) { JavaPlugin.log(ex); MessageDialog.openError(shell, errorTitle, errorMessage); } finally { if (buffer != null) TextBuffer.release(buffer); } } /** * Creates a TextEdit for inserting the given lines into the container. */ private TextEdit createEdit(String[] lines, IParent container) { // find a child where to insert before IJavaElement[] children= null; try { children= container.getChildren(); } catch(JavaModelException ex) { } if (children != null) { IJavaElement candidate= null; for (int i= 0; i < children.length; i++) { IJavaElement chld= children[i]; switch (chld.getElementType()) { case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: // skip these but remember the last of them candidate= chld; continue; default: return new MemberEdit(chld, MemberEdit.INSERT_BEFORE, lines, CodeFormatterPreferencePage.getTabSize()); } } if (candidate != null) return new MemberEdit(candidate, MemberEdit.INSERT_AFTER, lines, CodeFormatterPreferencePage.getTabSize()); } // no children: insert at end (but before closing bracket) if (container instanceof IJavaElement) return new MemberEdit((IJavaElement)container, MemberEdit.ADD_AT_END, lines, CodeFormatterPreferencePage.getTabSize()); return null; } protected boolean isEnabled(ISelection selection) { if (selection.isEmpty()) { if (fEditor != null) { // we check whether editor shows CompilationUnit IEditorInput editorInput= fEditor.getEditorInput(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(editorInput) != null; } return false; } if (selection instanceof IStructuredSelection) { Object o= ((IStructuredSelection)selection).getFirstElement(); if (o instanceof ICompilationUnit) return true; } return super.isEnabled(selection); } }
12,861
Bug 12861 Replace from local history does not always preserve line delimiters.
If a history file contains the two line delimiters '\r\n\r' the second '\r' is not preserved.
resolved fixed
ad1b0fa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-05T12:45:14Z
2002-04-05T12:33:20Z
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.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 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)); 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; } /** * Breaks the given string into lines and strips off the line terminator. */ static String[] readLines(InputStream is) { try { StringBuffer sb= null; List list= new ArrayList(); while (true) { int c= is.read(); if (c == -1) break; if (c == '\n' || c == '\r') { if (sb != null) list.add(sb.toString()); sb= null; } else { if (sb == null) sb= new StringBuffer(); sb.append((char)c); } } if (sb != null) 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) { } } } } }
12,861
Bug 12861 Replace from local history does not always preserve line delimiters.
If a history file contains the two line delimiters '\r\n\r' the second '\r' is not preserved.
resolved fixed
ad1b0fa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-05T12:45:14Z
2002-04-05T12:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaReplaceWithEditionAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.lang.reflect.InvocationTargetException; import java.util.ResourceBundle; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ISelection; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.internal.corext.codemanipulation.MemberEdit; import org.eclipse.jdt.internal.corext.textmanipulation.*; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.compare.JavaHistoryAction.JavaTextBufferNode; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.compare.*; import org.eclipse.compare.internal.TimeoutContext; /** * Provides "Replace from local history" for Java elements. */ public class JavaReplaceWithEditionAction extends JavaHistoryAction { private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.ReplaceWithEditionAction"; //$NON-NLS-1$ private boolean fPrevious= false; public JavaReplaceWithEditionAction() { } public JavaReplaceWithEditionAction(boolean previous) { fPrevious= previous; } // CompareMessages.getString("ReplaceFromHistory.action.label") protected ITypedElement[] buildEditions(ITypedElement target, IFile file, IFileState[] states) { ITypedElement[] editions= new ITypedElement[states.length+1]; editions[0]= new ResourceNode(file); for (int i= 0; i < states.length; i++) editions[i+1]= new HistoryItem(target, states[i]); return editions; } /** * @see Action#run */ public void run(IAction action) { String errorTitle= CompareMessages.getString("ReplaceFromHistory.title"); //$NON-NLS-1$ String errorMessage= CompareMessages.getString("ReplaceFromHistory.internalErrorMessage"); //$NON-NLS-1$ Shell shell= JavaPlugin.getActiveWorkbenchShell(); // shell can be null; as a result error dialogs won't be parented ISelection selection= getSelection(); IMember input= getEditionElement(selection); if (input == null) { // shouldn't happen because Action should not be enabled in the first place MessageDialog.openError(shell, errorTitle, errorMessage); return; } IFile file= getFile(input); if (file == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } boolean inEditor= beingEdited(file); if (inEditor) input= (IMember) getWorkingCopy(input); // get a TextBuffer where to insert the text TextBuffer buffer= null; try { buffer= TextBuffer.acquire(file); ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME); EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle); ITypedElement target= new JavaTextBufferNode(buffer, inEditor); ITypedElement[] editions= buildEditions(target, file); ITypedElement ti= null; if (fPrevious) ti= d.selectPreviousEdition(target, editions, input); else ti= d.selectEdition(target, editions, input); if (ti instanceof IStreamContentAccessor) { // from the edition get the lines (text) to insert String[] lines= null; try { lines= JavaCompareUtilities.readLines(((IStreamContentAccessor) ti).getContents()); } catch (CoreException ex) { JavaPlugin.log(ex); } if (lines == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } TextEdit edit= new MemberEdit(input, MemberEdit.REPLACE, lines, CodeFormatterPreferencePage.getTabSize()); IProgressMonitor nullProgressMonitor= new NullProgressMonitor(); TextBufferEditor editor= new TextBufferEditor(buffer); editor.add(edit); editor.performEdits(nullProgressMonitor); final TextBuffer bb= buffer; IRunnableWithProgress r= new IRunnableWithProgress() { public void run(IProgressMonitor pm) throws InvocationTargetException { try { TextBuffer.commitChanges(bb, false, pm); } catch (CoreException ex) { throw new InvocationTargetException(ex); } } }; if (inEditor) { // we don't show progress r.run(nullProgressMonitor); } else { ProgressMonitorDialog pd= new ProgressMonitorDialog(shell); pd.run(true, false, r); } } } catch(InvocationTargetException ex) { JavaPlugin.log(ex); MessageDialog.openError(shell, errorTitle, errorMessage); } catch(InterruptedException ex) { // shouldn't be called because is not cancable } catch(CoreException ex) { JavaPlugin.log(ex); MessageDialog.openError(shell, errorTitle, errorMessage); } finally { if (buffer != null) TextBuffer.release(buffer); } } }
13,012
Bug 13012 Exception in NLS refactoring
Build 20020404+ Got the following exception when using the NLS wizard (pressing next on first page) Log: Mon Apr 08 18:41:40 CEST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.ArrayList.toArray(ArrayList.java:288) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.getAllFilesToModi fy(NLSRefactoring.java:253) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.validateModifiesF iles(NLSRefactoring.java:257) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.checkInput (NLSRefactoring.java:221) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:98)
resolved fixed
6c71de9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-08T16:51:22Z
2002-04-08T15:33:20Z
org.eclipse.jdt.ui/core
13,012
Bug 13012 Exception in NLS refactoring
Build 20020404+ Got the following exception when using the NLS wizard (pressing next on first page) Log: Mon Apr 08 18:41:40 CEST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.ArrayList.toArray(ArrayList.java:288) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.getAllFilesToModi fy(NLSRefactoring.java:253) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.validateModifiesF iles(NLSRefactoring.java:257) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.checkInput (NLSRefactoring.java:221) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:58) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:93) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:98)
resolved fixed
6c71de9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-08T16:51:22Z
2002-04-08T15:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSRefactoring.java
6,532
Bug 6532 Templates - Insert variable -- popup doesn't disappear
Window/Preferences/Java/Templates: Once one clicked on the "Insert variable" button one cannot make the popup window disappear without clicking on the "pattern" TA. Even when I switch to another application the window stays open! The window should disappear once the user clicks outside the popup window and/or changes (-> loss of focus) to another application. @@@@ Sebastian Davids
closed fixed
d07d014
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T10:44:53Z
2001-12-04T04:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/EditTemplateDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; 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.Font; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.template.ContextType; import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateContext; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplateTranslator; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.text.template.TemplateVariableProcessor; import org.eclipse.jdt.internal.ui.util.SWTUtil; /** * Dialog to edit a template. */ public class EditTemplateDialog extends StatusDialog { private static class SimpleJavaSourceViewerConfiguration extends JavaSourceViewerConfiguration { private final IContentAssistProcessor fProcessor; SimpleJavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, IContentAssistProcessor processor) { super(tools, editor); fProcessor= processor; } /* * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { ContentAssistant assistant= new ContentAssistant(); assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE); assistant.enableAutoActivation(true); assistant.setAutoActivationDelay(500); assistant.setProposalPopupOrientation(assistant.PROPOSAL_OVERLAY); assistant.setContextInformationPopupOrientation(assistant.CONTEXT_INFO_ABOVE); assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); Color background= getColorManager().getColor(new RGB(254, 241, 233)); assistant.setContextInformationPopupBackground(background); assistant.setContextSelectorBackground(background); assistant.setProposalSelectorBackground(background); return assistant; } } private static class TextViewerAction extends Action implements IUpdate { private int fOperationCode= -1; private ITextOperationTarget fOperationTarget; public TextViewerAction(ITextViewer viewer, int operationCode) { fOperationCode= operationCode; fOperationTarget= viewer.getTextOperationTarget(); update(); } /** * Updates the enabled state of the action. * Fires a property change if the enabled state changes. * * @see Action#firePropertyChange(String, Object, Object) */ public void update() { boolean wasEnabled= isEnabled(); boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); setEnabled(isEnabled); if (wasEnabled != isEnabled) { firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE); } } /** * @see Action#run() */ public void run() { if (fOperationCode != -1 && fOperationTarget != null) { fOperationTarget.doOperation(fOperationCode); } } } private Template fTemplate; private Text fNameText; private Text fDescriptionText; private Combo fContextCombo; private SourceViewer fPatternEditor; private Button fInsertVariableButton; private TemplateTranslator fTranslator= new TemplateTranslator(); private boolean fSuppressError= true; // #4354 private Map fGlobalActions= new HashMap(10); private List fSelectionActions = new ArrayList(3); private Vector fContextTypes= new Vector(); private final TemplateVariableProcessor fProcessor= new TemplateVariableProcessor(); public EditTemplateDialog(Shell parent, Template template, boolean edit) { super(parent); setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE); String title= edit ? TemplateMessages.getString("EditTemplateDialog.title.edit") //$NON-NLS-1$ : TemplateMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$ setTitle(title); fTemplate= template; ContextTypeRegistry registry= ContextTypeRegistry.getInstance(); for (Iterator iterator= registry.iterator(); iterator.hasNext(); ) fContextTypes.add(iterator.next()); if (fContextTypes.size() > 0) fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType((String) fContextTypes.get(0))); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite ancestor) { Composite parent= new Composite(ancestor, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; parent.setLayout(layout); parent.setLayoutData(new GridData(GridData.FILL_BOTH)); createLabel(parent, TemplateMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$ Composite composite= new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layout= new GridLayout(); layout.numColumns= 3; layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); fNameText= createText(composite); fNameText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (fSuppressError && (fNameText.getText().trim().length() != 0)) fSuppressError= false; updateButtons(); } }); createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$ fContextCombo= new Combo(composite, SWT.READ_ONLY); for (Iterator iterator= fContextTypes.iterator(); iterator.hasNext(); ) fContextCombo.add((String) iterator.next()); fContextCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String name= fContextCombo.getText(); fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType(name)); } }); createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$ fDescriptionText= createText(parent); composite= new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); createLabel(composite, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ fPatternEditor= createEditor(parent); Label filler= new Label(composite, SWT.NONE); filler.setLayoutData(new GridData(GridData.FILL_VERTICAL)); fInsertVariableButton= new Button(composite, SWT.NONE); fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton)); fInsertVariableButton.setText(TemplateMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ fInsertVariableButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); } public void widgetDefaultSelected(SelectionEvent e) {} }); fNameText.setText(fTemplate.getName()); fDescriptionText.setText(fTemplate.getDescription()); fContextCombo.select(getIndex(fTemplate.getContextTypeName())); initializeActions(); return composite; } private static GridData getButtonGridData(Button button) { GridData data= new GridData(GridData.FILL_HORIZONTAL); data.heightHint= SWTUtil.getButtonHeigthHint(button); return data; } private static Label createLabel(Composite parent, String name) { Label label= new Label(parent, SWT.NULL); label.setText(name); label.setLayoutData(new GridData()); return label; } private static Text createText(Composite parent) { Text text= new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return text; } private SourceViewer createEditor(Composite parent) { SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); viewer.configure(new SimpleJavaSourceViewerConfiguration(tools, null, fProcessor)); viewer.setEditable(true); viewer.setDocument(new Document(fTemplate.getPattern())); Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT); viewer.getTextWidget().setFont(font); Control control= viewer.getControl(); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(60); data.heightHint= convertHeightInCharsToPixels(5); control.setLayoutData(data); viewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { try { fTranslator.translate(event.getDocumentEvent().getDocument().get()); } catch (CoreException e) { JavaPlugin.log(e); // XXX dialog } updateUndoAction(); updateButtons(); } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateSelectionDependentActions(); } }); viewer.getTextWidget().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } public void keyReleased(KeyEvent e) {} }); return viewer; } private void handleKeyPressed(KeyEvent event) { if (event.stateMask != SWT.CTRL) return; switch (event.character) { case ' ': fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); break; // XXX CTRL-Z case (int) 'z' - (int) 'a' + 1: fPatternEditor.doOperation(ITextOperationTarget.UNDO); break; } } private void initializeActions() { TextViewerAction action= new TextViewerAction(fPatternEditor, fPatternEditor.UNDO); action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.UNDO, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.CUT); action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.CUT, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.COPY); action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.COPY, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.PASTE); action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.PASTE, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.SELECT_ALL); action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.CONTENTASSIST_PROPOSALS); action.setText(TemplateMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$ fSelectionActions.add(ITextEditorActionConstants.CUT); fSelectionActions.add(ITextEditorActionConstants.COPY); fSelectionActions.add(ITextEditorActionConstants.PASTE); // create context menu MenuManager manager= new MenuManager(null, null); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { fillContextMenu(mgr); } }); StyledText text= fPatternEditor.getTextWidget(); Menu menu= manager.createContextMenu(text); text.setMenu(menu); } private void fillContextMenu(IMenuManager menu) { menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ } protected void updateSelectionDependentActions() { Iterator iterator= fSelectionActions.iterator(); while (iterator.hasNext()) updateAction((String)iterator.next()); } protected void updateUndoAction() { IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO); if (action instanceof IUpdate) ((IUpdate) action).update(); } protected void updateAction(String actionId) { IAction action= (IAction) fGlobalActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } private int getIndex(String context) { ContextTypeRegistry registry= ContextTypeRegistry.getInstance(); registry.getContextType(context); if (context == null) return -1; return fContextTypes.indexOf(context); } protected void okPressed() { fTemplate.setName(fNameText.getText()); fTemplate.setDescription(fDescriptionText.getText()); fTemplate.setContext(fContextCombo.getText()); fTemplate.setPattern(fPatternEditor.getTextWidget().getText()); super.okPressed(); } private void updateButtons() { boolean valid= fNameText.getText().trim().length() != 0; StatusInfo status= new StatusInfo(); if (!valid) { if (fSuppressError) status.setError(""); //$NON-NLS-1$ else status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ } else if (fTranslator.getErrorMessage() != null) { status.setError(fTranslator.getErrorMessage()); } updateStatus(status); } }
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26:40Z
org.eclipse.jdt.ui/core
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OpenHierarchyAction.java
/* * (c) Copyright 2002 IBM Corporation. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.actions; import org.eclipse.swt.widgets.Event; import org.eclipse.jface.action.Action; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; /** * An action to open a type hierarchy either in its own perspective or * in the type hierarchy view part of the current perspective. */ public class OpenHierarchyAction extends Action { private IJavaElement[] fElements; private IWorkbenchWindow fWindow; public OpenHierarchyAction(IWorkbenchWindow window, IJavaElement[] elements) { fElements= elements; fWindow= window; setText(JavaUIMessages.getString("OpenHierarchyPerspectiveItem.menulabel")); //$NON-NLS-1$ } public void runWithEvent(Event event) { OpenTypeHierarchyUtil.open(fElements, fWindow, event.stateMask); } }
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/SelectionConverter.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.actions; import java.util.Arrays; import java.util.Iterator; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.ui.IWorkingCopyManager; public class SelectionConverter { private static final IJavaElement[] EMPTY_RESULT= new IJavaElement[0]; private SelectionConverter() { // no instance } public static IJavaElement[] getElements(IStructuredSelection selection) { if (!selection.isEmpty()) { IJavaElement[] result= new IJavaElement[selection.size()]; int i= 0; for (Iterator iter= selection.iterator(); iter.hasNext(); i++) { Object element= (Object) iter.next(); if (!(element instanceof IJavaElement)) return EMPTY_RESULT; result[i]= (IJavaElement)element; } return result; } return EMPTY_RESULT; } public static IJavaElement[] codeResolveOrInput(JavaEditor editor) throws JavaModelException { IJavaElement input= getInput(editor); ITextSelection selection= (ITextSelection)editor.getSelectionProvider().getSelection(); IJavaElement[] result= codeResolve(input, selection); if (result.length == 0 && selection.getLength() == 0) { result= new IJavaElement[] {input}; } return result; } public static IJavaElement codeResolveOrInput(JavaEditor editor, Shell shell, String title, String message) throws JavaModelException { IJavaElement[] elements= codeResolveOrInput(editor); if (elements == null || elements.length == 0) return null; IJavaElement candidate= elements[0]; if (elements.length > 1) { candidate= OpenActionUtil.selectJavaElement(Arrays.asList(elements), shell, title, message); } return candidate; } public static IJavaElement[] codeResolve(JavaEditor editor) throws JavaModelException { return codeResolve(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection()); } public static IJavaElement elementAtOffset(JavaEditor editor) throws JavaModelException { return elementAtOffset(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection()); } public static IJavaElement getInput(JavaEditor editor) { IEditorInput input= editor.getEditorInput(); if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(input); } private static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException { if (input instanceof ICodeAssist) { IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength()); if (elements != null && elements.length > 0) return elements; } return EMPTY_RESULT; } private static IJavaElement elementAtOffset(IJavaElement input, ITextSelection selection) throws JavaModelException { if (input instanceof ICompilationUnit) { ICompilationUnit cunit= (ICompilationUnit)input; if (cunit.isWorkingCopy()) { synchronized (cunit) { cunit.reconcile(); } } IJavaElement ref= cunit.getElementAt(selection.getOffset()); if (ref != null) { return ref; } } else if (input instanceof IClassFile) { IJavaElement ref= ((IClassFile)input).getElementAt(selection.getOffset()); if (ref != null) { return ref; } } return null; } }
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/StructuredSelectionProvider.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.actions; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.ISelectionService; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; /** */ public abstract class StructuredSelectionProvider { public static int FLAGS_DO_CODERESOLVE= 1; public static int FLAGS_DO_ELEMENT_AT_OFFSET= 2; public static int FLAGS_GET_EDITOR_INPUT= 4; private static abstract class Adapter extends StructuredSelectionProvider { private ITextSelection fLastTextSelection; private IStructuredSelection fLastStructuredSelection; private Adapter() { } protected IStructuredSelection asStructuredSelection(ITextSelection selection, int flags) throws CoreException { IEditorPart editor= JavaPlugin.getActivePage().getActiveEditor(); if (editor == null) return StructuredSelection.EMPTY; return asStructuredSelection(selection, editor, flags); } protected IStructuredSelection asStructuredSelection(ITextSelection selection, IEditorPart editor, int flags) throws CoreException { if ((flags & FLAGS_DO_CODERESOLVE) != 0) { IStructuredSelection result; if (!selection.isEmpty()) { result= considerCache(selection); if (result != null) return result; } IJavaElement assist= getEditorInput(editor); if (assist instanceof ICodeAssist) { IJavaElement[] elements= ((ICodeAssist)assist).codeSelect(selection.getOffset(), selection.getLength()); result= new StructuredSelection(elements); if (!selection.isEmpty()) cacheResult(selection, result); return result; } } if ((flags & FLAGS_DO_ELEMENT_AT_OFFSET) != 0) { IJavaElement assist= getEditorInput(editor); if (assist instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit) assist; if (cu.isWorkingCopy()) { synchronized (cu) { cu.reconcile(); } } IJavaElement ref= ((ICompilationUnit)assist).getElementAt(selection.getOffset()); if (ref != null) { return new StructuredSelection(ref); } } else if (assist instanceof IClassFile) { IJavaElement ref= ((IClassFile)assist).getElementAt(selection.getOffset()); if (ref != null) { return new StructuredSelection(ref); } } } if ((flags & FLAGS_GET_EDITOR_INPUT) != 0) { IJavaElement assist= getEditorInput(editor); if (assist != null) { return new StructuredSelection(assist); } } return StructuredSelection.EMPTY; } private IStructuredSelection considerCache(ITextSelection selection) { if (selection != fLastTextSelection) { fLastTextSelection= null; fLastStructuredSelection= null; } return fLastStructuredSelection; } private void cacheResult(ITextSelection selection, IStructuredSelection result) { fLastTextSelection= selection; fLastStructuredSelection= result; } private IJavaElement getEditorInput(IEditorPart editorPart) { IEditorInput input= editorPart.getEditorInput(); if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(input); } } private static class SelectionProviderAdapter extends Adapter { private ISelectionProvider fProvider; public SelectionProviderAdapter(ISelectionProvider provider) { super(); fProvider= provider; Assert.isNotNull(fProvider); } public IStructuredSelection getSelection(int flags) { try { ISelection result= fProvider.getSelection(); if (result instanceof IStructuredSelection) return (IStructuredSelection)result; if (result instanceof ITextSelection && fProvider instanceof IEditorPart) return asStructuredSelection((ITextSelection)result, (IEditorPart)fProvider, flags); } catch (CoreException e) { JavaPlugin.log(e); } return StructuredSelection.EMPTY; } } private static class SelectionServiceAdapter extends Adapter { private ISelectionService fService; public SelectionServiceAdapter(ISelectionService service) { super(); fService= service; Assert.isNotNull(fService); } public IStructuredSelection getSelection(int flags) { try { ISelection result= fService.getSelection(); if (result instanceof IStructuredSelection) return (IStructuredSelection)result; if (result instanceof ITextSelection) return asStructuredSelection((ITextSelection)result, flags); } catch (CoreException e) { JavaPlugin.log(e); } return StructuredSelection.EMPTY; } } /** * Returns the current selection. Does not return <code>null</code>, but the empty selection * in case no selected element could be found. * For text selections the element referenced at the current position is taken. */ public IStructuredSelection getSelection() { return getSelection(FLAGS_DO_CODERESOLVE); } /** * Returns the current selection. Does not return <code>null</code>, but the empty selection * in case no selected element could be found. * @param flags Defines how text selections should be processed. FLAGS_DO_CODERESOLVE or * FLAGS_DO_ELEMENT_AT_OFFSET, FLAGS_GET_EDITOR_INPUT are valid options. */ public abstract IStructuredSelection getSelection(int flags); private StructuredSelectionProvider() { // prevent instantiation. } public static StructuredSelectionProvider createFrom(ISelectionProvider provider) { return new SelectionProviderAdapter(provider); } public static StructuredSelectionProvider createFrom(ISelectionService service) { return new SelectionServiceAdapter(service); } }
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; 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.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.DecoratingLabelProvider; 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.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.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.IPartListener; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.NewWizardMenu; import org.eclipse.ui.actions.OpenPerspectiveMenu; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.actions.RefreshAction; import org.eclipse.ui.dialogs.PropertyDialogAction; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.views.internal.framelist.BackAction; import org.eclipse.ui.views.internal.framelist.ForwardAction; import org.eclipse.ui.views.internal.framelist.GoIntoAction; import org.eclipse.ui.views.internal.framelist.UpAction; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.core.JavaElement; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.packageview.BuildGroup; import org.eclipse.jdt.internal.ui.packageview.OpenResourceAction; import org.eclipse.jdt.internal.ui.packageview.PackagesMessages; import org.eclipse.jdt.internal.ui.packageview.ShowInNavigatorAction; import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.OpenActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener { private ILabelProvider fLabelProvider; private ILabelProvider fTitleProvider; private StructuredViewer fViewer; private IMemento fMemento; private JavaElementTypeComparator fTypeComparator; // Actions private ContextMenuGroup[] fStandardGroups; private Menu fContextMenu; private OpenResourceAction fOpenCUAction; private Action fOpenToAction; private Action fShowNavigatorAction; private PropertyDialogAction fPropertyDialogAction; private IRefactoringAction fDeleteAction; private RefreshAction fRefreshAction; private BackAction fBackAction; private ForwardAction fForwardAction; private GoIntoAction fZoomInAction; private UpAction fUpAction; // private GotoTypeAction fGotoTypeAction; // private GotoPackageAction fGotoPackageAction; private IWorkbenchPart fPreviousSelectionProvider; private Image fOriginalTitleImage; private ActionGroup fStandardActionGroups; /* * Ensure selection changed events being processed only if * initiated by user interaction with this part. */ private boolean fProcessSelectionEvents= true; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { setSelectionFromEditor(part); } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; /* * Implements method from IViewPart. */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } // XXX: need to save state here // fViewer.saveState(memento); } /** * Creates the search list inner viewer. */ public void createPartControl(Composite parent) { Assert.isTrue(fViewer == null); if (fMemento != null) // XXX: Restore state here // fViewer.restoreState(fMemento); fMemento= null; fTypeComparator= new JavaElementTypeComparator(); // Setup viewer fViewer= createViewer(parent); fLabelProvider= createLabelProvider(); ILabelDecorator decorationMgr= PlatformUI.getWorkbench().getDecoratorManager(); fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr)); fViewer.setSorter(new JavaElementSorter()); fViewer.setUseHashlookup(true); JavaPlugin.getDefault().getProblemMarkerManager().addListener((IProblemChangedListener)fViewer); fTitleProvider= createTitleProvider(); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getControl()); fViewer.getControl().setMenu(fContextMenu); getSite().registerContextMenu(menuMgr, fViewer); createActions(); // call before registering for selection changes addKeyListener(); getSite().setSelectionProvider(fViewer); // Status line IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); hookViewerListeners(); // Initialize viewer input fViewer.setContentProvider(createContentProvider()); setInitialInput(); // Initialize selecton setInitialSelection(); // Filters addFilters(); fillToolBar(getViewSite().getActionBars().getToolBarManager()); // Listen to workbench window changes getViewSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this); getViewSite().getPage().addPartListener(fPartListener); fStandardActionGroups= new CompositeActionGroup(new ActionGroup[] { new OpenActionGroup(this), new ShowActionGroup(this), new GenerateActionGroup(this)}); fStandardActionGroups.fillActionBars(getViewSite().getActionBars()); setHelp(); } //---- IWorkbenchPart ------------------------------------------------------ public void setFocus() { fViewer.getControl().setFocus(); } public void dispose() { if (fViewer != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener((IProblemChangedListener)fViewer); getViewSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this); getViewSite().getPage().removePartListener(fPartListener); fViewer= null; } super.dispose(); } /** * Adds the KeyListener */ protected void addKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { handleKeyReleased(event); } }); } protected void handleKeyReleased(KeyEvent event) { if (event.stateMask != 0) return; int key= event.keyCode; if (key == SWT.F5) { fRefreshAction.selectionChanged( (IStructuredSelection) fViewer.getSelection()); if (fRefreshAction.isEnabled()) fRefreshAction.run(); } if (event.character == SWT.DEL) { fDeleteAction.update(); if (fDeleteAction.isEnabled()) fDeleteAction.run(); } } //---- Adding Action to Toolbar ------------------------------------------- protected void fillToolBar(IToolBarManager tbm) { // fViewer.fillToolBar(tbm); } // protected void setContextMenuContributor(final IContextMenuContributor contributor) { // // Make sure we are doing it in the right thread. // getDisplay().syncExec(new Runnable() { // public void run() { //// getViewer().setContextMenuTarget(contributor); // } // }); // } /** * Called when the context menu is about to open. * Override to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); fPropertyDialogAction.selectionChanged(selection); MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$ menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu); new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false); // updateActions(selection); // Object element= selection.getFirstElement(); // if (selection.size() == 1 && fViewer.isExpandable(element)) // menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction); // addGotoMenu(menu); // // Open menus fOpenCUAction.update(); if (fOpenCUAction.isEnabled()) menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction); addOpenWithMenu(menu, selection); addOpenToMenu(menu, selection); addRefactoring(menu); ContextMenuGroup.add(menu, fStandardGroups, fViewer); menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction); fRefreshAction.selectionChanged(selection); menu.add(new Separator()); if (fPropertyDialogAction.isApplicableForSelection()) menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction); } private void addRefactoring(IMenuManager menu){ MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void createActions() { ISelectionProvider provider= getSelectionProvider(); fOpenCUAction= new OpenResourceAction(provider); fPropertyDialogAction= new PropertyDialogAction(getShell(), provider); fShowNavigatorAction= new ShowInNavigatorAction(provider); fStandardGroups= new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup(), new GenerateGroup(), new JavaSearchGroup() }; fDeleteAction= ReorgGroup.createDeleteAction(provider); fRefreshAction= new RefreshAction(getShell()); // fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$ // fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$ // fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$ // fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$ // fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$ // fBackAction= new BackAction(fFrameList); // fForwardAction= new ForwardAction(fFrameList); // fZoomInAction= new GoIntoAction(fFrameList); // fUpAction= new UpAction(fFrameList); // fGotoTypeAction= new GotoTypeAction(this); // fGotoPackageAction= new GotoPackageAction(this); IActionBars actionService= getViewSite().getActionBars(); actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction); ReorgGroup.addGlobalReorgActions(actionService, provider); } private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) { if (selection.size() != 1) return; IAdaptable element= (IAdaptable) selection.getFirstElement(); IResource resource= (IResource)element.getAdapter(IResource.class); if ((resource instanceof IContainer)) { // Create a menu flyout. MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$ submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource)); menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; IAdaptable element= (IAdaptable)selection.getFirstElement(); Object resource= element.getAdapter(IResource.class); if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } /** * Returns the shell to use for opening dialogs. * Used in this class, and in the actions. */ private Shell getShell() { return fViewer.getControl().getShell(); } protected final Display getDisplay() { return fViewer.getControl().getDisplay(); } /** * Returns the selection provider. */ private ISelectionProvider getSelectionProvider() { return fViewer; } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ abstract protected boolean isValidInput(Object element); /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element == null) return false; element= getSuitableJavaElement(element); if (element == null) return false; Object input= getViewer().getInput(); if (input == null) return false; if (input instanceof Collection) return ((Collection)input).contains(element); else return input.equals(element); } private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) { if (newInput == null) return part == fPreviousSelectionProvider; if (input instanceof IJavaElement && newInput instanceof IJavaElement) return getTypeComparator().compare(newInput, input) > 0; else return false; } private boolean isInputResetBy(IWorkbenchPart part) { if (!(part instanceof JavaBrowsingPart)) return true; Object thisInput= getViewer().getInput(); Object partInput= ((JavaBrowsingPart)part).getViewer().getInput(); if (thisInput instanceof IJavaElement && partInput instanceof IJavaElement) return getTypeComparator().compare(partInput, thisInput) > 0; else return true; } protected boolean isAncestorOf(Object ancestor, Object element) { if (element instanceof IJavaElement && ancestor instanceof IJavaElement) return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element); return false; } private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) { if (element != null) return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent()); else return false; } public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!fProcessSelectionEvents || part == this || !(selection instanceof IStructuredSelection)) return; // Set selection Object selectedElement= getSingleElementFromSelection(selection); Object currentInput= (IJavaElement)getViewer().getInput(); if (selectedElement != null && selectedElement.equals(currentInput)) { IJavaElement elementToSelect= findElementToSelect(getSingleElementFromSelection(selection)); if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0) setSelection(new StructuredSelection(elementToSelect), true); fPreviousSelectionProvider= part; return; } // Clear input if needed if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) { if (!isAncestorOf(selectedElement, currentInput)) setInput(null); fPreviousSelectionProvider= part; return; } else if (selection.isEmpty() && !isInputResetBy(part)) { fPreviousSelectionProvider= part; return; } else if (selectedElement == null && part == fPreviousSelectionProvider) { setInput(null); fPreviousSelectionProvider= part; return; } fPreviousSelectionProvider= part; // Adjust input and set selection and if (selectedElement instanceof IJavaElement) adjustInputAndSetSelection((IJavaElement)selectedElement); else setSelection(StructuredSelection.EMPTY, true); } protected void setInput(Object input) { if (input == null) setTitleImage(fOriginalTitleImage); else if (input instanceof Collection) { if (((Collection)input).isEmpty()) setTitleImage(fOriginalTitleImage); else { Object firstElement= ((Collection)input).iterator().next(); setTitleImage(fTitleProvider.getImage(firstElement)); } } else setTitleImage(fTitleProvider.getImage(input)); setViewerInput(input); } private void setViewerInput(Object input) { fProcessSelectionEvents= false; fViewer.setInput(input); fProcessSelectionEvents= true; } /** * Sets or clears the title image of this part and * store the orignal image on the first call. */ protected void setTitleImage(Image titleImage) { if (fOriginalTitleImage == null) fOriginalTitleImage= getTitleImage(); if (titleImage == null) titleImage= fOriginalTitleImage; super.setTitleImage(titleImage); } protected final StructuredViewer getViewer() { return fViewer; } protected ILabelProvider createLabelProvider() { return new StandardJavaUILabelProvider( StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS, StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, StandardJavaUILabelProvider.getAdornmentProviders(true, null) ); } protected ILabelProvider createTitleProvider() { return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS); } protected final ILabelProvider getLabelProvider() { return fLabelProvider; } protected final ILabelProvider getTitleProvider() { return fTitleProvider; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { return new ProblemTableViewer(parent, SWT.MULTI); } protected int getLabelProviderFlags() { return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS; } /** * Adds filters the viewer of this part. */ protected void addFilters() { // default is to have no filters } /** * Creates the the content provider of this part. */ protected BaseJavaElementContentProvider createContentProvider() { return new JavaElementContentProvider(true, this); // } protected void setInitialInput() { // Use the selection, if any ISelection selection= getSite().getPage().getSelection(); Object input= getSingleElementFromSelection(selection); if (!(input instanceof IJavaElement)) { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement) && input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); } setInput(findInputForJavaElement((JavaElement)input)); } protected void setInitialSelection() { // Use the selection, if any Object input; ISelection selection= getSite().getPage().getSelection(); if (selection != null && !selection.isEmpty()) input= getSingleElementFromSelection(selection); else { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement) && input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); else return; } if (findElementToSelect((IJavaElement)input) != null) adjustInputAndSetSelection((IJavaElement)input); } final protected void setHelp() { JavaUIHelp.setHelp(fViewer, getHelpContextId()); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ abstract protected String getHelpContextId(); /** * Adds additional listeners to this view. */ protected void hookViewerListeners() { fViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!fProcessSelectionEvents) return; if (JavaBrowsingPreferencePage.openEditorOnSingleClick()) new ShowInEditorAction().run(event.getSelection(), getSite().getPage()); else linkToEditor((IStructuredSelection)event.getSelection()); } }); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (fProcessSelectionEvents && !JavaBrowsingPreferencePage.openEditorOnSingleClick()) new ShowInEditorAction().run(event.getSelection(), getSite().getPage()); } }); } void adjustInputAndSetSelection(IJavaElement je) { je= getSuitableJavaElement(je); IJavaElement elementToSelect= findElementToSelect(je); IJavaElement newInput= findInputForJavaElement(je); if (elementToSelect == null && !isValidInput(newInput)) // Clear input setInput(null); else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) // Adjust input to selection setInput(findInputForJavaElement(je)); if (elementToSelect != null) setSelection(new StructuredSelection(elementToSelect), true); else setSelection(StructuredSelection.EMPTY, true); } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; if (isValidInput(je)) return je; return findInputForJavaElement(je.getParent()); } final protected IJavaElement findElementToSelect(Object obj) { if (obj instanceof IJavaElement) return findElementToSelect((IJavaElement)obj); return null; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ abstract protected IJavaElement findElementToSelect(IJavaElement je); private Object getSingleElementFromSelection(ISelection selection) { if (!(selection instanceof StructuredSelection) || selection.isEmpty()) return null; Iterator iter= ((StructuredSelection)selection).iterator(); Object firstElement= iter.next(); if (!(firstElement instanceof IJavaElement)) return firstElement; Object currentInput= (IJavaElement)getViewer().getInput(); if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaElement)firstElement))) if (iter.hasNext()) // multi selection and view is empty return null; else // ok: single selection and view is empty return firstElement; // be nice to multi selection while (iter.hasNext()) { Object element= iter.next(); if (!(element instanceof IJavaElement)) return null; if (!currentInput.equals(findInputForJavaElement((IJavaElement)element))) return null; } return firstElement; } /** * Gets the typeComparator. * @return Returns a JavaElementTypeComparator */ protected Comparator getTypeComparator() { return fTypeComparator; } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { if (selection == null || selection.isEmpty()) return; Object obj= selection.getFirstElement(); Object element= null; if (selection.size() == 1) { if (obj instanceof IJavaElement) { IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT); if (cu != null) element= getResourceFor(cu); if (element == null) element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE); } else if (obj instanceof IFile) element= obj; if (element == null) return; IWorkbenchPage page= getSite().getPage(); IEditorPart editorArray[]= page.getEditors(); for (int i= 0; i < editorArray.length; ++i) { IEditorPart editor= editorArray[i]; Object input= getElementOfInput(editor.getEditorInput()); if (input != null && input.equals(element)) { page.bringToTop(editor); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(editor, (IJavaElement) obj); return; } } } } private void setSelectionFromEditor(IWorkbenchPart part) { if (part == null) return; IWorkbenchPartSite site= part.getSite(); if (site == null) return; ISelectionProvider provider= site.getSelectionProvider(); if (provider != null) setSelectionFromEditor(part, provider.getSelection()); } private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) { if (part instanceof IEditorPart && JavaBrowsingPreferencePage.linkViewSelectionToEditor()) { IEditorInput ei= ((IEditorPart)part).getEditorInput(); if (selection instanceof ITextSelection) { int offset= ((ITextSelection)selection).getOffset(); IJavaElement element= getElementForInputAt(ei, offset); if (element != null) { adjustInputAndSetSelection(element); return; } } if (ei instanceof IFileEditorInput) { IFile file= ((IFileEditorInput)ei).getFile(); IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class); if (je == null) { setSelection(null, false); return; } adjustInputAndSetSelection(je); } else if (ei instanceof IClassFileEditorInput) { IClassFile cf= ((IClassFileEditorInput)ei).getClassFile(); adjustInputAndSetSelection(cf); } return; } } /** * 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; } private IResource getResourceFor(Object element) { if (element instanceof IJavaElement) { if (element instanceof IWorkingCopy) { IWorkingCopy wc= (IWorkingCopy)element; IJavaElement original= wc.getOriginalElement(); if (original != null) element= original; } try { element= ((IJavaElement)element).getUnderlyingResource(); } catch (JavaModelException e) { return null; } } if (!(element instanceof IResource) || ((IResource)element).isPhantom()) { return null; } return (IResource)element; } private void setSelection(ISelection selection, boolean reveal) { if (selection != null && selection.equals(fViewer.getSelection())) return; fProcessSelectionEvents= false; fViewer.setSelection(selection, reveal); fProcessSelectionEvents= true; } /** * Tries to find the given element in a workingcopy. */ protected static IJavaElement getWorkingCopy(IJavaElement input) { try { if (input instanceof ICompilationUnit) return EditorUtility.getWorkingCopy((ICompilationUnit)input); else return EditorUtility.getWorkingCopy(input, true); } catch (JavaModelException ex) { } return null; } /** * Returns the original element from which the specified working copy * element was created from. This is a handle only method, the * returned element may or may not exist. * * @param workingCopy the element for which to get the original * @return the original Java element or <code>null</code> if this is not a working copy element */ protected static IJavaElement getOriginal(IJavaElement workingCopy) { ICompilationUnit cu= getCompilationUnit(workingCopy); if (cu != null) return ((IWorkingCopy)cu).getOriginal(workingCopy); return null; } /** * Returns the compilation unit for the given java element. * * @param element the java element whose compilation unit is searched for * @return the compilation unit of the given java element */ protected static ICompilationUnit getCompilationUnit(IJavaElement element) { if (element == null) return null; if (element instanceof IMember) return ((IMember) element).getCompilationUnit(); int type= element.getElementType(); if (IJavaElement.COMPILATION_UNIT == type) return (ICompilationUnit) element; if (IJavaElement.CLASS_FILE == type) return null; return getCompilationUnit(element.getParent()); } /** * Converts the given Java element to one which is suitable for this * view. It takes into account wether the view shows working copies or not. * * @param element the Java element to be converted * @return an element suitable for this view */ protected IJavaElement getSuitableJavaElement(Object obj) { if (!(obj instanceof IJavaElement)) return null; IJavaElement element= (IJavaElement)obj; if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0) return element; if (element.getElementType() == IJavaElement.CLASS_FILE) return element; if (((BaseJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy()) { IJavaElement wc= getWorkingCopy(element); if (wc != null) element= wc; return element; } else { ICompilationUnit cu= getCompilationUnit(element); if (cu != null && ((IWorkingCopy)cu).isWorkingCopy()) return ((IWorkingCopy)cu).getOriginal(element); else return element; } } /** * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementForInputAt(IEditorInput input, int offset) { if (input instanceof IClassFileEditorInput) { try { return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset); } catch (JavaModelException ex) { return null; } } IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(input); if (unit != null) synchronized (unit) { try { unit.reconcile(); return unit.getElementAt(offset); } catch (JavaModelException x) { } } return null; } protected IType getTypeForCU(ICompilationUnit cu) { cu= (ICompilationUnit)getSuitableJavaElement(cu); // Use primary type if possible IType primaryType= JavaModelUtil.findPrimaryType(cu); if (primaryType != null) return primaryType; // Use first top-level type try { IType[] types= cu.getTypes(); if (types.length > 0) return types[0]; else return null; } catch (JavaModelException ex) { return null; } } }
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26: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.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.Shell; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.action.Action; 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.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelDecorator; 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.ITreeViewerListener; 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.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; 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.IPartListener; 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.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.AddBookmarkAction; import org.eclipse.ui.actions.NewWizardMenu; import org.eclipse.ui.actions.OpenPerspectiveMenu; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.actions.RefreshAction; import org.eclipse.ui.dialogs.PropertyDialogAction; import org.eclipse.ui.part.ISetSelectionTarget; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.views.framelist.BackAction; import org.eclipse.ui.views.framelist.ForwardAction; import org.eclipse.ui.views.framelist.FrameList; import org.eclipse.ui.views.framelist.GoIntoAction; import org.eclipse.ui.views.framelist.UpAction; import org.eclipse.search.ui.IWorkingSet; import org.eclipse.search.ui.SearchUI; 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.IMember; import org.eclipse.jdt.core.IOpenable; 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.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.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; 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.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterActionGroup; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IPackagesViewPart; import org.eclipse.jdt.ui.JavaElementContentProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.OpenActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; /** * 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, IPackagesViewPart, IPropertyChangeListener { 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_SHOWLIBRARIES = "showLibraries"; //$NON-NLS-1$ static final String TAG_SHOWBINARIES = "showBinaries"; //$NON-NLS-1$ static final String TAG_WORKINGSET = "workingset"; //$NON-NLS-1$ private JavaElementPatternFilter fPatternFilter= new JavaElementPatternFilter(); private LibraryFilter fLibraryFilter= new LibraryFilter(); private BinaryProjectFilter fBinaryFilter= new BinaryProjectFilter(); private WorkingSetFilter fWorkingSetFilter= new WorkingSetFilter(); private MemberFilterActionGroup fMemberFilterActionGroup; private ProblemTreeViewer fViewer; private StandardJavaUILabelProvider fJavaElementLabelProvider; private PackagesFrameSource fFrameSource; private FrameList fFrameList; private ContextMenuGroup[] fStandardGroups; private Menu fContextMenu; private OpenResourceAction fOpenCUAction; private Action fOpenToAction; private Action fShowTypeHierarchyAction; private Action fShowNavigatorAction; private PropertyDialogAction fPropertyDialogAction; private IRefactoringAction fDeleteAction; private RefreshAction fRefreshAction; private BackAction fBackAction; private ForwardAction fForwardAction; private GoIntoAction fZoomInAction; private UpAction fUpAction; private GotoTypeAction fGotoTypeAction; private GotoPackageAction fGotoPackageAction; private AddBookmarkAction fAddBookmarkAction; private FilterSelectionAction fFilterAction; private ShowLibrariesAction fShowLibrariesAction; private ShowBinariesAction fShowBinariesAction; private FilterWorkingSetAction fFilterWorkingSetAction; private RemoveWorkingSetFilterAction fRemoveWorkingSetAction; private IMemento fMemento; private ISelectionChangedListener fSelectionListener; private ActionGroup fStandardActionGroups; 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); } }; public PackageExplorerPart() { } /* (non-Javadoc) * Method declared on IViewPart. */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /** * Initializes the default preferences */ public static void initDefaults(IPreferenceStore store) { store.setDefault(TAG_SHOWLIBRARIES, true); store.setDefault(TAG_SHOWBINARIES, 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() { IViewPart view= JavaPlugin.getActivePage().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 (fViewer != null) JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fViewer); if (fContextMenu != null && !fContextMenu.isDisposed()) fContextMenu.dispose(); getSite().getPage().removePartListener(fPartListener); JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); if (fViewer != null) fViewer.removeTreeListener(fExpansionListener); super.dispose(); } /** * Implementation of IWorkbenchPart.createPartControl(Composite) */ public void createPartControl(Composite parent) { fViewer= new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren(); fViewer.setContentProvider(new JavaElementContentProvider(showCUChildren, false)); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fViewer); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); fJavaElementLabelProvider= new StandardJavaUILabelProvider( StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED, StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, StandardJavaUILabelProvider.getAdornmentProviders(true, null) ); fViewer.setLabelProvider(new DecoratingLabelProvider( fJavaElementLabelProvider, PlatformUI.getWorkbench().getDecoratorManager()) ); fViewer.setSorter(new JavaElementSorter()); fViewer.addFilter(new EmptyInnerPackageFilter()); fViewer.setUseHashlookup(true); fViewer.addFilter(fPatternFilter); fViewer.addFilter(fLibraryFilter); fMemberFilterActionGroup= new MemberFilterActionGroup(fViewer, "PackageView"); // adds filter fViewer.addFilter(fWorkingSetFilter); if(fMemento != null) restoreFilters(); else initFilterFromPreferences(); // Set input after filter and sorter has been set. This avoids resorting // and refiltering. fViewer.setInput(findInputElement()); initDragAndDrop(); initFrameList(); initKeyListener(); updateTitle(); 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); makeActions(); // call before registering for selection changes fSelectionListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { handleSelectionChanged(event); } }; fViewer.addSelectionChangedListener(fSelectionListener); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { handleDoubleClick(event); } }); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); fViewer.addTreeListener(fExpansionListener); if (fMemento != null) restoreState(fMemento); fMemento= null; // Set help for the view JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW); fillActionBars(); } private void fillActionBars() { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager toolBar= actionBars.getToolBarManager(); fillToolBar(toolBar); actionBars.updateActionBars(); IMenuManager menu= actionBars.getMenuManager(); menu.add(fFilterAction); menu.add(fShowLibrariesAction); //menu.add(fShowBinariesAction); menu.add(fFilterWorkingSetAction); menu.add(fRemoveWorkingSetAction); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$ fStandardActionGroups.fillActionBars(actionBars); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.REFRESH, fRefreshAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmarkAction); // Navigate Go Into and Go To actions. actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BACK, fBackAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.FORWARD, fForwardAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction); ReorgGroup.addGlobalReorgActions(actionBars, getSelectionProvider()); } private void fillToolBar(IToolBarManager toolBar) { toolBar.removeAll(); toolBar.add(fBackAction); toolBar.add(fForwardAction); toolBar.add(fUpAction); if (JavaBasePreferencePage.showCompilationUnitChildren()) { toolBar.add(new Separator()); fMemberFilterActionGroup.contributeToToolBar(toolBar); } } private Object findInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IWorkspace) { return JavaCore.create(((IWorkspace)input).getRoot()); } else if (input instanceof IContainer) { return JavaCore.create((IContainer)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; return super.getAdapter(key); } /** * Returns the tool tip text for the given element. */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { result= JavaElementLabels.getTextLabel(element, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$ } else { result= path.makeRelative().toString(); } } IWorkingSet ws= fWorkingSetFilter.getWorkingSet(); if (ws == null) return result; String wsstr= "Working Set: "+ws.getName(); if (result.length() == 0) return wsstr; return result + " - " + wsstr; } public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } /** * @see IWorkbenchPart#setFocus() */ public void setFocus() { fViewer.getTree().setFocus(); } /** * Sets the working set to be used for filtering this part */ public void setWorkingSet(IWorkingSet ws) { fWorkingSetFilter.setWorkingSet(ws); firePropertyChange(IWorkbenchPart.PROP_TITLE); fFilterWorkingSetAction.setChecked(ws != null); fRemoveWorkingSetAction.setEnabled(ws != null); } /** * Returns the shell to use for opening dialogs. * Used in this class, and in the actions. */ private Shell getShell() { return fViewer.getTree().getShell(); } /** * Returns the selection provider. */ private ISelectionProvider getSelectionProvider() { return fViewer; } /** * 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); IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); Object element= selection.getFirstElement(); fPropertyDialogAction.selectionChanged(selection); MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$ menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu); new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false); // updateActions(selection); if (selection.size() == 1 && fViewer.isExpandable(element)) menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction); addGotoMenu(menu); fOpenCUAction.update(); if (fOpenCUAction.isEnabled()) menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction); addOpenWithMenu(menu, selection); addOpenToMenu(menu, selection); addRefactoring(menu); ContextMenuGroup.add(menu, fStandardGroups, fViewer); if (onlyFilesSelected(selection)) { menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddBookmarkAction); } menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction); menu.add(new Separator()); if (fPropertyDialogAction.isApplicableForSelection()) menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction); } void addGotoMenu(IMenuManager menu) { MenuManager gotoMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.gotoTitle")); //$NON-NLS-1$ menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, gotoMenu); gotoMenu.add(fBackAction); gotoMenu.add(fForwardAction); gotoMenu.add(fUpAction); gotoMenu.add(fGotoTypeAction); gotoMenu.add(fGotoPackageAction); } private boolean onlyFilesSelected(IStructuredSelection selection) { if (selection.isEmpty()) return false; for (Iterator enum= selection.iterator(); enum.hasNext();) { Object o= enum.next(); if (o instanceof IFile) continue; if (o instanceof IAdaptable) { Object resource= ((IAdaptable)o).getAdapter(IResource.class); if (!(resource instanceof IFile)) return false; } else { return false; } } return true; } private void makeActions() { ISelectionProvider provider= getSelectionProvider(); fOpenCUAction= new OpenResourceAction(provider); fPropertyDialogAction= new PropertyDialogAction(getShell(), provider); // fShowTypeHierarchyAction= new ShowTypeHierarchyAction(provider); fShowNavigatorAction= new ShowInNavigatorAction(provider); fAddBookmarkAction= new AddBookmarkAction(getShell()); provider.addSelectionChangedListener(fAddBookmarkAction); fStandardGroups= new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup(), new GenerateGroup(), new JavaSearchGroup() }; fStandardActionGroups= new CompositeActionGroup(new ActionGroup[] { new OpenActionGroup(this), new ShowActionGroup(this), new GenerateActionGroup(this)}); fDeleteAction= ReorgGroup.createDeleteAction(provider); fRefreshAction= new RefreshAction(getShell()); provider.addSelectionChangedListener(fRefreshAction); fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$ fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$ fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$ fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$ fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$ fBackAction= new BackAction(fFrameList); fForwardAction= new ForwardAction(fFrameList); fZoomInAction= new GoIntoAction(fFrameList); fUpAction= new UpAction(fFrameList); fGotoTypeAction= new GotoTypeAction(this); fGotoPackageAction= new GotoPackageAction(this); } private void addRefactoring(IMenuManager menu){ MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) { if (selection.size() != 1) return; IAdaptable element= (IAdaptable) selection.getFirstElement(); IResource resource= (IResource)element.getAdapter(IResource.class); if ((resource instanceof IContainer)) { // Create a menu flyout. MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$ submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource)); menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; IAdaptable element= (IAdaptable)selection.getFirstElement(); Object resource= element.getAdapter(IResource.class); if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) { if (! (s instanceof IStructuredSelection) || s.isEmpty()) return false; IStructuredSelection selection= (IStructuredSelection)s; Iterator iter= selection.iterator(); while (iter.hasNext()) { Object o= iter.next(); if (clazz.isInstance(o)) return true; if (considerUnderlyingResource) { if (! (o instanceof IJavaElement)) return false; IJavaElement element= (IJavaElement)o; Object resource= element.getAdapter(IResource.class); if (! clazz.isInstance(resource)) return false; } } return true; } //---- Event handling ---------------------------------------------------------- private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE; final LocalSelectionTransfer lt= LocalSelectionTransfer.getInstance(); Transfer[] transfers= new Transfer[] { lt, ResourceTransfer.getInstance(), FileTransfer.getInstance()}; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fViewer), new FileTransferDropAdapter(fViewer) }; fViewer.addDropSupport(ops, 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)); } /** * Handles double clicks in viewer. * Opens editor if file double-clicked. */ private void handleDoubleClick(DoubleClickEvent event) { IStructuredSelection s= (IStructuredSelection) event.getSelection(); Object element= s.getFirstElement(); if (fOpenCUAction.isEnabled()) { fOpenCUAction.run(); return; } if (fViewer.isExpandable(element)) { if (JavaBasePreferencePage.doubleClickGoesInto()) { // don't zoom into compilation units and class files if (element instanceof IOpenable && !(element instanceof ICompilationUnit) && !(element instanceof IClassFile)) { fZoomInAction.run(); } } else { fViewer.setExpandedState(element, !fViewer.getExpandedState(element)); //expandMainType(element); } } } /** * Handles selection changed in viewer. * Updates global actions. * Links to editor (if option enabled) */ private void handleSelectionChanged(SelectionChangedEvent event) { IStructuredSelection selection= (IStructuredSelection) event.getSelection(); //updateGlobalActions(sel); fZoomInAction.update(); linkToEditor(selection); } public void selectReveal(ISelection selection) { ISelection javaSelection= convertSelection(selection); fViewer.setSelection(javaSelection, true); } private ISelection convertSelection(ISelection s) { List converted= new ArrayList(); if (s instanceof StructuredSelection) { Object[] elements= ((StructuredSelection)s).toArray(); for (int i= 0; i < elements.length; i++) { Object e= elements[i]; if (e instanceof IJavaElement) converted.add(e); else if (e instanceof IResource) { IJavaElement element= JavaCore.create((IResource)e); if (element != null) converted.add(element); else converted.add(e); } } } return new StructuredSelection(converted.toArray()); } public void selectAndReveal(Object element) { selectReveal(new StructuredSelection(element)); } /** * Returns whether the preference to link selection to active editor is enabled. */ boolean isLinkingEnabled() { return JavaBasePreferencePage.linkPackageSelectionToEditor(); } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { //if (!isLinkingEnabled()) // return; Object obj= selection.getFirstElement(); Object element= null; if (selection.size() == 1) { if (obj instanceof IJavaElement) { IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT); if (cu != null) element= getResourceFor(cu); if (element == null) element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE); } else if (obj instanceof IFile) element= obj; if (element == null) return; IWorkbenchPage page= getSite().getPage(); IEditorPart editorArray[]= page.getEditors(); for (int i= 0; i < editorArray.length; ++i) { IEditorPart editor= editorArray[i]; Object input= getElementOfInput(editor.getEditorInput()); if (input != null && input.equals(element)) { page.bringToTop(editor); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(editor, (IJavaElement) obj); return; } } } } private IResource getResourceFor(Object element) { if (element instanceof IJavaElement) { if (element instanceof IWorkingCopy) { IWorkingCopy wc= (IWorkingCopy)element; IJavaElement original= wc.getOriginalElement(); if (original != null) element= original; } try { element= ((IJavaElement)element).getUnderlyingResource(); } catch (JavaModelException e) { return null; } } if (!(element instanceof IResource) || ((IResource)element).isPhantom()) { return null; } return (IResource)element; } 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); saveScrollState(memento, fViewer.getTree()); savePatternFilterState(memento); saveFilterState(memento); saveWorkingSetState(memento); saveMemberFilterState(memento); } protected void saveFilterState(IMemento memento) { boolean showLibraries= getLibraryFilter().getShowLibraries(); String show= "true"; //$NON-NLS-1$ if (!showLibraries) show= "false"; //$NON-NLS-1$ memento.putString(TAG_SHOWLIBRARIES, show); //save binary filter boolean showBinaries= getBinaryFilter().getShowBinaries(); String showBinString= "true"; //$NON-NLS-1$ if (!showBinaries) showBinString= "false"; //$NON-NLS-1$ memento.putString(TAG_SHOWBINARIES, showBinString); } protected void savePatternFilterState(IMemento memento) { String filters[] = getPatternFilter().getPatterns(); if(filters.length > 0) { IMemento filtersMem = memento.createChild(TAG_FILTERS); for (int i = 0; i < filters.length; i++){ IMemento child = filtersMem.createChild(TAG_FILTER); child.putString(TAG_ELEMENT,filters[i]); } } } 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.getExpandedElements(); 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()); } } } protected void saveWorkingSetState(IMemento memento) { IWorkingSet ws= getWorkingSetFilter().getWorkingSet(); if (ws != null) { memento.putString(TAG_WORKINGSET, ws.getName()); } } /** * Saves the state of the filter actions */ public void saveMemberFilterState(IMemento memento) { fMemberFilterActionGroup.saveState(memento); } void restoreState(IMemento memento) { restoreExpansionState(memento); restoreSelectionState(memento); restoreScrollState(memento, fViewer.getTree()); } 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)); 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)); 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) { doKeyPressed(event); } }); } private void doKeyPressed(KeyEvent event) { if (event.stateMask != 0) return; int key= event.keyCode; if (event.character == SWT.DEL){ fDeleteAction.update(); if (fDeleteAction.isEnabled()) fDeleteAction.run(); } } void initFrameList() { fFrameSource= new PackagesFrameSource(this); fFrameList= new FrameList(fFrameSource); fFrameSource.connectTo(fFrameList); } /** * An editor has been activated. Set the selection in this Packages Viewer * to be the editor's input, if linking is enabled. */ void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) return; Object input= getElementOfInput(editor.getEditorInput()); Object element= null; if (input instanceof IFile) element= JavaCore.create((IFile)input); if (element == null) // try a non Java resource element= input; if (element != null) { // if the current selection is a child of the new // selection then ignore it. IStructuredSelection oldSelection= (IStructuredSelection)getSelection(); if (oldSelection.size() == 1) { Object o= oldSelection.getFirstElement(); if (o instanceof IMember) { IMember m= (IMember)o; if (element.equals(m.getCompilationUnit())) return; if (element.equals(m.getClassFile())) return; } } ISelection newSelection= new StructuredSelection(element); if (!fViewer.getSelection().equals(newSelection)) { try { fViewer.removeSelectionChangedListener(fSelectionListener); fViewer.setSelection(newSelection); } finally { fViewer.addSelectionChangedListener(fSelectionListener); } } } } /** * 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 pattern filter for this view. * @return the pattern filter */ JavaElementPatternFilter getPatternFilter() { return fPatternFilter; } /** * Returns the library filter for this view. * @return the library filter */ LibraryFilter getLibraryFilter() { return fLibraryFilter; } /** * Returns the working set filter for this view. * @return the working set filter */ WorkingSetFilter getWorkingSetFilter() { return fWorkingSetFilter; } /** * Returns the Binary filter for this view. * @return the binary filter */ BinaryProjectFilter getBinaryFilter() { return fBinaryFilter; } void restoreFilters() { IMemento filtersMem= fMemento.getChild(TAG_FILTERS); if(filtersMem != null) { IMemento children[]= filtersMem.getChildren(TAG_FILTER); String filters[]= new String[children.length]; for (int i = 0; i < children.length; i++) { filters[i]= children[i].getString(TAG_ELEMENT); } getPatternFilter().setPatterns(filters); } else { getPatternFilter().setPatterns(new String[0]); } //restore library String show= fMemento.getString(TAG_SHOWLIBRARIES); if (show != null) getLibraryFilter().setShowLibraries(show.equals("true")); //$NON-NLS-1$ else initLibraryFilterFromPreferences(); //restore binary fileter String showbin= fMemento.getString(TAG_SHOWBINARIES); if (showbin != null) getBinaryFilter().setShowBinaries(showbin.equals("true")); //$NON-NLS-1$ else initBinaryFilterFromPreferences(); //restore working set String workingSetName= fMemento.getString(TAG_WORKINGSET); if (workingSetName != null) { IWorkingSet ws= SearchUI.findWorkingSet(workingSetName); if (ws != null) { getWorkingSetFilter().setWorkingSet(ws); } } fMemberFilterActionGroup.restoreState(fMemento); } void initFilterFromPreferences() { initBinaryFilterFromPreferences(); initLibraryFilterFromPreferences(); } void initLibraryFilterFromPreferences() { JavaPlugin plugin= JavaPlugin.getDefault(); boolean show= plugin.getPreferenceStore().getBoolean(TAG_SHOWLIBRARIES); getLibraryFilter().setShowLibraries(show); } void initBinaryFilterFromPreferences() { JavaPlugin plugin= JavaPlugin.getDefault(); boolean showbin= plugin.getPreferenceStore().getBoolean(TAG_SHOWBINARIES); getBinaryFilter().setShowBinaries(showbin); } boolean isExpandable(Object element) { if (fViewer == null) return false; return fViewer.isExpandable(element); } /** * Updates the title text and title tool tip. * Called whenever the input of the viewer changes. */ void updateTitle() { Object input= getViewer().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, StandardJavaUILabelProvider.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) { if (decorator == null) fViewer.setLabelProvider(fJavaElementLabelProvider); else fViewer.setLabelProvider(new DecoratingLabelProvider(fJavaElementLabelProvider, decorator)); } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fViewer == null) return; boolean refreshViewer= false; if (event.getProperty() == JavaBasePreferencePage.SHOW_CU_CHILDREN) { IActionBars actionBars= getViewSite().getActionBars(); fillToolBar(actionBars.getToolBarManager()); actionBars.updateActionBars(); boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren(); ((JavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren); refreshViewer= true; } if (refreshViewer) fViewer.refresh(); } }
12,525
Bug 12525 NPE in extract method
in junit.awtui.TestRunner in the method createUI try to extract the following range: Panel numbersPanel= <START>new Panel(new FlowLayout()); numbersPanel.add(new Label("Runs:")); numbersPanel.add(fNumberOfRuns); numbersPanel.add(new Label(" Errors:")); numbersPanel.add(fNumberOfErrors); numbersPanel.add(new Label(" Failures:")); numbersPanel.add (fNumberOfFailures); <END> You get a walkback: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.handleNextSelectedNode (SelectionAnalyzer.java:97) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.handleNex tSelectedNode(ExtractMethodAnalyzer.java:384) at org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer.visitNode (SelectionAnalyzer.java:73) at org.eclipse.jdt.internal.corext.dom.GenericVisitor.visit (GenericVisitor.java:83) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0 (ExpressionStatement.java:71) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:73) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:173) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkA ctivation(ExtractMethodRefactoring.java:161) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:74) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionAction.run (TextSelectionAction.java:80) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(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:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
resolved fixed
81bed90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T13:16:18Z
2002-03-31T21:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/OpenTypeHierarchyUtil.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.util; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.core.runtime.CoreException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveRegistry; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPreferenceConstants; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.internal.WorkbenchPlugin; 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.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.actions.OpenHierarchyAction; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaUI; public class OpenTypeHierarchyUtil { private OpenTypeHierarchyUtil() { } public static boolean canOperateOn(ISelection s) { Object element= getElement(s); return (element != null) ? (getCandidates(element) != null) : false; } public static void addToMenu(IWorkbenchWindow window, IMenuManager menu, ISelection s) { addToMenu(window, menu, getElement(s)); } public static void addToMenu(IWorkbenchWindow window, IMenuManager menu, Object element) { IJavaElement[] candidates= getCandidates(element); if (candidates != null) { menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, new OpenHierarchyAction(window, candidates)); } } public static TypeHierarchyViewPart open(ISelection selection, IWorkbenchWindow window) { Object element= getElement(selection); if (element instanceof IJavaElement) { return open((IJavaElement)element, window); } return null; } public static TypeHierarchyViewPart open(IJavaElement element, IWorkbenchWindow window) { IJavaElement[] candidates= getCandidates(element); if (candidates != null) { return open(candidates, window); } return null; } public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) { return open(candidates, window, 0); } public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window, int mask) { Assert.isTrue(candidates != null && candidates.length != 0); IJavaElement input= null; if (candidates.length > 1) { input= selectCandidate(candidates, window.getShell()); } else { input= candidates[0]; } if (input == null) return null; try { if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { return openInPerspective(window, input, mask); } else { return openInViewPart(window, input); } } catch (WorkbenchException e) { JavaPlugin.log(e); MessageDialog.openError(window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$ e.getMessage()); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); MessageDialog.openError(window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$ e.getMessage()); } return null; } private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) { IWorkbenchPage page= window.getActivePage(); try { // 1GEUMSG: ITPJUI:WINNT - Class hierarchy not shown when fast view if (input instanceof IMember) { openEditor(input); } TypeHierarchyViewPart result= (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); result.setInputElement(input); if (input instanceof IMember) { result.selectMember((IMember) input); } return result; } catch (CoreException e) { JavaPlugin.log(e.getStatus()); MessageDialog.openError(window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$ } return null; } private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement input, int mask) throws WorkbenchException, JavaModelException { IPreferenceStore store= WorkbenchPlugin.getDefault().getPreferenceStore(); String mode= store.getString(IWorkbenchPreferenceConstants.OPEN_NEW_PERSPECTIVE); IWorkbenchPage page= null; if (IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_WINDOW.equals(mode)) { page= openWindow(input, mask); } else if (IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_PAGE.equals(mode)) { page= openPage(window, input, mask); } if (input instanceof IMember) { openEditor(input); } return (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); } private static void openEditor(Object input) throws PartInitException, JavaModelException { IEditorPart part= EditorUtility.openInEditor(input, true); if (input instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) input); } private static IWorkbenchPage openWindow(IJavaElement input, int mask) throws WorkbenchException, JavaModelException { return PlatformUI.getWorkbench().openPage(JavaUI.ID_HIERARCHYPERSPECTIVE, input, mask); } private static IWorkbenchPage openPage(IWorkbenchWindow window, IJavaElement input, int mask) throws WorkbenchException, JavaModelException { IWorkbenchPage page= null; /* * not implementable in the current form. See http://dev.eclipse.org/bugs/show_bug.cgi?id=3962 if (JavaBasePreferencePage.reusePerspectiveForTypeHierarchy()) { page= findPage(window); if (page != null) { window.setActivePage(page); TypeHierarchyViewPart part= (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); if (input instanceof IType) part.setInputElement((IType)input); } } */ if (page == null) { page= PlatformUI.getWorkbench().openPage(JavaUI.ID_HIERARCHYPERSPECTIVE, input, mask); } return page; } private static IWorkbenchPage findPage(IWorkbenchWindow window) { IPerspectiveRegistry registry= PlatformUI.getWorkbench().getPerspectiveRegistry(); IPerspectiveDescriptor pd= registry.findPerspectiveWithId(JavaUI.ID_HIERARCHYPERSPECTIVE); IWorkbenchPage pages[]= window.getPages(); for (int i= 0; i < pages.length; i++) { IWorkbenchPage page= pages[i]; if (page.getPerspective().equals(pd)) return page; } return null; } private static IJavaElement selectCandidate(IJavaElement[] candidates, Shell shell) { int flags= (JavaElementLabelProvider.SHOW_DEFAULT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaElementLabelProvider(flags)); dialog.setTitle(JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title")); //$NON-NLS-1$ dialog.setMessage(JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message")); //$NON-NLS-1$ dialog.setElements(candidates); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); if ((elements != null) && (elements.length == 1)) return (IJavaElement) elements[0]; } return null; } private static Object getElement(ISelection s) { if (!(s instanceof IStructuredSelection)) return null; IStructuredSelection selection= (IStructuredSelection)s; if (selection.size() != 1) return null; return selection.getFirstElement(); } /** * Converts the input to a possible input candidates */ public static IJavaElement[] getCandidates(Object input) { if (!(input instanceof IJavaElement)) { return null; } try { IJavaElement elem= (IJavaElement) input; switch (elem.getElementType()) { case IJavaElement.INITIALIZER: case IJavaElement.METHOD: case IJavaElement.FIELD: case IJavaElement.TYPE: case IJavaElement.PACKAGE_FRAGMENT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.JAVA_PROJECT: return new IJavaElement[] { elem }; case IJavaElement.CLASS_FILE: return new IJavaElement[] { ((IClassFile)input).getType() }; case IJavaElement.COMPILATION_UNIT: case IJavaElement.IMPORT_CONTAINER: case IJavaElement.IMPORT_DECLARATION: case IJavaElement.PACKAGE_DECLARATION: { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT); if (cu != null) { IType[] types= cu.getTypes(); if (types.length > 0) { return types; } } break; } default: } } catch (JavaModelException e) { JavaPlugin.log(e); } return null; } }
12,911
Bug 12911 Open Type dialog doesn't always combine types with same name
Build 20020321 Create the following three classes: bar.FOO baz.Foo quux.FOO Now open the 'Open Type' dialog, and type in 'foo'. The list will have three entries in it: +-----+ | FOO | | Foo | | FOO | +-----+ This is incorrect. The two 'FOO' entries should be combined, and the list should look like: +-----+ | FOO | | Foo | +-----+ I suspect that this is due to a compare function which doesn't distinguish between strings which only differ by case, causing them to appear in an arbitrary order in a sorted list.
resolved fixed
e3ff955
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-09T14:00:59Z
2002-04-05T23:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TypeSelectionDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.internal.corext.util.AllTypesCache; import org.eclipse.jdt.internal.corext.util.TypeInfo; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.StringMatcher; import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider; /** * A dialog to select a type from a list of types. */ public class TypeSelectionDialog extends TwoPaneElementSelector { private static class TypeFilterMatcher implements FilteredList.FilterMatcher { private StringMatcher fMatcher; private StringMatcher fQualifierMatcher; /* * @see FilteredList.FilterMatcher#setFilter(String, boolean) */ public void setFilter(String pattern, boolean ignoreCase, boolean igoreWildCards) { int qualifierIndex= pattern.lastIndexOf("."); //$NON-NLS-1$ // type if (qualifierIndex == -1) { fQualifierMatcher= null; fMatcher= new StringMatcher(pattern + '*', ignoreCase, igoreWildCards); // qualified type } else { fQualifierMatcher= new StringMatcher(pattern.substring(0, qualifierIndex), ignoreCase, igoreWildCards); fMatcher= new StringMatcher(pattern.substring(qualifierIndex + 1), ignoreCase, igoreWildCards); } } /* * @see FilteredList.FilterMatcher#match(Object) */ public boolean match(Object element) { if (!(element instanceof TypeInfo)) return false; TypeInfo type= (TypeInfo) element; if (!fMatcher.match(type.getTypeName())) return false; if (fQualifierMatcher == null) return true; return fQualifierMatcher.match(type.getTypeContainerName()); } } /* * A string comparator which is aware of obfuscated code * (type names starting with lower case characters). */ private static class StringComparator implements Comparator { public int compare(Object left, Object right) { String leftString= (String) left; String rightString= (String) right; if (Character.isLowerCase(leftString.charAt(0)) && !Character.isLowerCase(rightString.charAt(0))) return +1; if (Character.isLowerCase(rightString.charAt(0)) && !Character.isLowerCase(leftString.charAt(0))) return -1; return leftString.compareToIgnoreCase(rightString); } } private IRunnableContext fRunnableContext; private IJavaSearchScope fScope; private int fElementKinds; /** * Constructs a type selection dialog. * @param parent the parent shell. * @param context the runnable context. * @param elementKinds <code>IJavaSearchConstants.CLASS</code>, <code>IJavaSearchConstants.INTERFACE</code> * or <code>IJavaSearchConstants.TYPE</code> * @param scope the java search scope. */ public TypeSelectionDialog(Shell parent, IRunnableContext context, int elementKinds, IJavaSearchScope scope) { super(parent, new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeInfoLabelProvider.SHOW_ROOT_POSTFIX)); Assert.isNotNull(context); Assert.isNotNull(scope); fRunnableContext= context; fScope= scope; fElementKinds= elementKinds; setUpperListLabel(JavaUIMessages.getString("TypeSelectionDialog.upperLabel")); //$NON-NLS-1$ setLowerListLabel(JavaUIMessages.getString("TypeSelectionDialog.lowerLabel")); //$NON-NLS-1$ } public void create() { // if (getFilter() == null) // setFilter("A"); //$NON-NLS-1$ super.create(); } /* * @see AbstractElementListSelectionDialog#createFilteredList(Composite) */ protected FilteredList createFilteredList(Composite parent) { FilteredList list= super.createFilteredList(parent); fFilteredList.setFilterMatcher(new TypeFilterMatcher()); fFilteredList.setComparator(new StringComparator()); return list; } /** * @see Window#open() */ public int open() { final ArrayList typeList= new ArrayList(); if (AllTypesCache.isCacheUpToDate()) { // run without progress monitor try { AllTypesCache.getTypes(fScope, fElementKinds, null, typeList); } catch (JavaModelException e) { ExceptionHandler.handle(e, "Exception", "Unexpected exception. See log for details."); return CANCEL; } } else { IRunnableWithProgress runnable= new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { AllTypesCache.getTypes(fScope, fElementKinds, monitor, typeList); } catch (JavaModelException e) { throw new InvocationTargetException(e); } if (monitor.isCanceled()) { throw new InterruptedException(); } } }; try { fRunnableContext.run(true, true, runnable); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, "Exception", "Unexpected exception. See log for details."); return CANCEL; } catch (InterruptedException e) { // cancelled by user return CANCEL; } } if (typeList.isEmpty()) { String title= JavaUIMessages.getString("TypeSelectionDialog.notypes.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.notypes.message"); //$NON-NLS-1$ MessageDialog.openInformation(getShell(), title, message); return CANCEL; } TypeInfo[] typeRefs= (TypeInfo[])typeList.toArray(new TypeInfo[typeList.size()]); setElements(typeRefs); return super.open(); } /** * @see SelectionStatusDialog#computeResult() */ protected void computeResult() { TypeInfo ref= (TypeInfo) getLowerSelectedElement(); if (ref == null) return; try { IType type= ref.resolveType(fScope); if (type == null) { // not a class file or compilation unit String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); setResult(null); } else { List result= new ArrayList(1); result.add(type); setResult(result); } } catch (JavaModelException e) { String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); setResult(null); } } }
13,206
Bug 13206 Missing resource
20020409: Package View>Context Menu>OpenNewWindowAction.text
resolved fixed
5ba0c30
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-11T08:34:36Z
2002-04-10T12:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; 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.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.DecoratingLabelProvider; 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.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; 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.IPartListener; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.NewWizardMenu; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.actions.RefreshAction; import org.eclipse.ui.dialogs.PropertyDialogAction; import org.eclipse.ui.internal.OpenNewWindowAction; 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.IWorkingCopy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.OpenActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.core.JavaElement; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.packageview.BuildGroup; import org.eclipse.jdt.internal.ui.packageview.OpenResourceAction; import org.eclipse.jdt.internal.ui.packageview.PackagesMessages; import org.eclipse.jdt.internal.ui.packageview.ShowInNavigatorAction; import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener { private ILabelProvider fLabelProvider; private ILabelProvider fTitleProvider; private StructuredViewer fViewer; private IMemento fMemento; private JavaElementTypeComparator fTypeComparator; // Actions private ContextMenuGroup[] fStandardGroups; private Menu fContextMenu; private OpenResourceAction fOpenCUAction; private Action fOpenToAction; private Action fShowNavigatorAction; private PropertyDialogAction fPropertyDialogAction; private IRefactoringAction fDeleteAction; private RefreshAction fRefreshAction; private IWorkbenchPart fPreviousSelectionProvider; private Object fPreviousSelectedElement; private Image fOriginalTitleImage; private PatchedOpenNewWindowAction fBrowseAction; private ActionGroup fStandardActionGroups; /* * Ensure selection changed events being processed only if * initiated by user interaction with this part. */ private boolean fProcessSelectionEvents= true; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { setSelectionFromEditor(part); } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; /* * Implements method from IViewPart. */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } // XXX: need to save state here // fViewer.saveState(memento); } /** * Creates the search list inner viewer. */ public void createPartControl(Composite parent) { Assert.isTrue(fViewer == null); if (fMemento != null) // XXX: Restore state here // fViewer.restoreState(fMemento); fMemento= null; fTypeComparator= new JavaElementTypeComparator(); // Setup viewer fViewer= createViewer(parent); fLabelProvider= createLabelProvider(); ILabelDecorator decorationMgr= PlatformUI.getWorkbench().getDecoratorManager(); fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr)); fViewer.setSorter(new JavaElementSorter()); fViewer.setUseHashlookup(true); JavaPlugin.getDefault().getProblemMarkerManager().addListener((IProblemChangedListener)fViewer); fTitleProvider= createTitleProvider(); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getControl()); fViewer.getControl().setMenu(fContextMenu); getSite().registerContextMenu(menuMgr, fViewer); getSite().setSelectionProvider(fViewer); createActions(); // call before registering for selection changes addKeyListener(); getSite().setSelectionProvider(fViewer); // Status line IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); hookViewerListeners(); // Initialize viewer input fViewer.setContentProvider(createContentProvider()); setInitialInput(); // Initialize selecton setInitialSelection(); // Filters addFilters(); // Listen to workbench window changes getViewSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this); getViewSite().getPage().addPartListener(fPartListener); fillActionBars(); setHelp(); } private void fillActionBars() { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager toolBar= actionBars.getToolBarManager(); fillToolBar(toolBar); actionBars.updateActionBars(); // IMenuManager menu= actionBars.getMenuManager(); // menu.add(fFilterAction); // menu.add(fShowLibrariesAction); //menu.add(fShowBinariesAction); // menu.add(fFilterWorkingSetAction); // menu.add(fRemoveWorkingSetAction); // // menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); // menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$ fStandardActionGroups.fillActionBars(actionBars); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.REFRESH, fRefreshAction); // actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmarkAction); ReorgGroup.addGlobalReorgActions(actionBars, getSelectionProvider()); } //---- IWorkbenchPart ------------------------------------------------------ public void setFocus() { fViewer.getControl().setFocus(); } public void dispose() { if (fViewer != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener((IProblemChangedListener)fViewer); getViewSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this); getViewSite().getPage().removePartListener(fPartListener); fViewer= null; } super.dispose(); } /** * Adds the KeyListener */ protected void addKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { handleKeyReleased(event); } }); } protected void handleKeyReleased(KeyEvent event) { if (event.stateMask != 0) return; int key= event.keyCode; if (key == SWT.F5) { fRefreshAction.selectionChanged( (IStructuredSelection) fViewer.getSelection()); if (fRefreshAction.isEnabled()) fRefreshAction.run(); } if (event.character == SWT.DEL) { fDeleteAction.update(); if (fDeleteAction.isEnabled()) fDeleteAction.run(); } } //---- Adding Action to Toolbar ------------------------------------------- protected void fillToolBar(IToolBarManager tbm) { } // protected void setContextMenuContributor(final IContextMenuContributor contributor) { // // Make sure we are doing it in the right thread. // getDisplay().syncExec(new Runnable() { // public void run() { //// getViewer().setContextMenuTarget(contributor); // } // }); // } /** * Called when the context menu is about to open. * Override to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); int size= selection.size(); fPropertyDialogAction.selectionChanged(selection); MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$ menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu); new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false); // Open menus fOpenCUAction.update(); if (fOpenCUAction.isEnabled()) menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction); addOpenWithMenu(menu, selection); if (size == 1) addOpenNewWindowAction(menu, selection.getFirstElement()); addRefactoring(menu); ContextMenuGroup.add(menu, fStandardGroups, fViewer); menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction); fRefreshAction.selectionChanged(selection); menu.add(new Separator()); if (fPropertyDialogAction.isApplicableForSelection()) menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction); } private void addOpenNewWindowAction(IMenuManager menu, Object element) { if (element instanceof IJavaElement) { try { element= ((IJavaElement)element).getCorrespondingResource(); } catch(JavaModelException e) { } } if (!(element instanceof IContainer)) return; menu.appendToGroup( IContextMenuConstants.GROUP_OPEN, new PatchedOpenNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element)); } private void addRefactoring(IMenuManager menu){ MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void createActions() { ISelectionProvider provider= getSelectionProvider(); fOpenCUAction= new OpenResourceAction(provider); fPropertyDialogAction= new PropertyDialogAction(getShell(), provider); fShowNavigatorAction= new ShowInNavigatorAction(provider); fStandardGroups= new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup(), new GenerateGroup(), new JavaSearchGroup() }; fStandardActionGroups= new CompositeActionGroup(new ActionGroup[] { new OpenActionGroup(this), new ShowActionGroup(this), new GenerateActionGroup(this)}); fDeleteAction= ReorgGroup.createDeleteAction(provider); fRefreshAction= new RefreshAction(getShell()); // fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$ // fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$ // fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$ // fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$ // fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$ IActionBars actionService= getViewSite().getActionBars(); actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction); ReorgGroup.addGlobalReorgActions(actionService, provider); // fBrowseAction= new BrowseAction(this); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; IAdaptable element= (IAdaptable)selection.getFirstElement(); Object resource= element.getAdapter(IResource.class); if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } /** * Returns the shell to use for opening dialogs. * Used in this class, and in the actions. */ private Shell getShell() { return fViewer.getControl().getShell(); } protected final Display getDisplay() { return fViewer.getControl().getDisplay(); } /** * Returns the selection provider. */ ISelectionProvider getSelectionProvider() { return fViewer; } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ abstract protected boolean isValidInput(Object element); /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element == null) return false; element= getSuitableJavaElement(element); if (element == null) return false; Object input= getViewer().getInput(); if (input == null) return false; if (input instanceof Collection) return ((Collection)input).contains(element); else return input.equals(element); } private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) { if (newInput == null) return part == fPreviousSelectionProvider; if (input instanceof IJavaElement && newInput instanceof IJavaElement) return getTypeComparator().compare(newInput, input) > 0; else return false; } private boolean isInputResetBy(IWorkbenchPart part) { if (!(part instanceof JavaBrowsingPart)) return true; Object thisInput= getViewer().getInput(); Object partInput= ((JavaBrowsingPart)part).getViewer().getInput(); if (thisInput instanceof IJavaElement && partInput instanceof IJavaElement) return getTypeComparator().compare(partInput, thisInput) > 0; else return true; } protected boolean isAncestorOf(Object ancestor, Object element) { if (element instanceof IJavaElement && ancestor instanceof IJavaElement) return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element); return false; } private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) { if (element != null) return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent()); else return false; } public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!fProcessSelectionEvents || part == this || !(selection instanceof IStructuredSelection)) return; // Set selection Object selectedElement= getSingleElementFromSelection(selection); if (selectedElement != null && part.equals(fPreviousSelectionProvider) && selectedElement.equals(fPreviousSelectedElement)) return; fPreviousSelectedElement= selectedElement; Object currentInput= (IJavaElement)getViewer().getInput(); if (selectedElement != null && selectedElement.equals(currentInput)) { IJavaElement elementToSelect= findElementToSelect(getSingleElementFromSelection(selection)); if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0) setSelection(new StructuredSelection(elementToSelect), true); fPreviousSelectionProvider= part; return; } // Clear input if needed if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) { if (!isAncestorOf(selectedElement, currentInput)) setInput(null); fPreviousSelectionProvider= part; return; } else if (selection.isEmpty() && !isInputResetBy(part)) { fPreviousSelectionProvider= part; return; } else if (selectedElement == null && part == fPreviousSelectionProvider) { setInput(null); fPreviousSelectionProvider= part; return; } fPreviousSelectionProvider= part; // Adjust input and set selection and if (selectedElement instanceof IJavaElement) adjustInputAndSetSelection((IJavaElement)selectedElement); else setSelection(StructuredSelection.EMPTY, true); } protected void setInput(Object input) { if (input == null) setTitleImage(fOriginalTitleImage); else if (input instanceof Collection) { if (((Collection)input).isEmpty()) setTitleImage(fOriginalTitleImage); else { Object firstElement= ((Collection)input).iterator().next(); setTitleImage(fTitleProvider.getImage(firstElement)); } } else setTitleImage(fTitleProvider.getImage(input)); setViewerInput(input); } private void setViewerInput(Object input) { fProcessSelectionEvents= false; fViewer.setInput(input); fProcessSelectionEvents= true; } /** * Sets or clears the title image of this part and * store the orignal image on the first call. */ protected void setTitleImage(Image titleImage) { if (fOriginalTitleImage == null) fOriginalTitleImage= getTitleImage(); if (titleImage == null) titleImage= fOriginalTitleImage; super.setTitleImage(titleImage); } protected final StructuredViewer getViewer() { return fViewer; } protected ILabelProvider createLabelProvider() { return new StandardJavaUILabelProvider( StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS, StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, StandardJavaUILabelProvider.getAdornmentProviders(true, null) ); } protected ILabelProvider createTitleProvider() { return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS); } protected final ILabelProvider getLabelProvider() { return fLabelProvider; } protected final ILabelProvider getTitleProvider() { return fTitleProvider; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { return new ProblemTableViewer(parent, SWT.MULTI); } protected int getLabelProviderFlags() { return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS; } /** * Adds filters the viewer of this part. */ protected void addFilters() { // default is to have no filters } /** * Creates the the content provider of this part. */ protected BaseJavaElementContentProvider createContentProvider() { return new JavaElementContentProvider(true, this); // } protected void setInitialInput() { // Use the selection, if any ISelection selection= getSite().getPage().getSelection(); Object input= getSingleElementFromSelection(selection); if (!(input instanceof IJavaElement)) { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement) && input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); } setInput(findInputForJavaElement((JavaElement)input)); } protected void setInitialSelection() { // Use the selection, if any Object input; ISelection selection= getSite().getPage().getSelection(); if (selection != null && !selection.isEmpty()) input= getSingleElementFromSelection(selection); else { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement)) { if (input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); else return; } } if (findElementToSelect((IJavaElement)input) != null) adjustInputAndSetSelection((IJavaElement)input); } final protected void setHelp() { JavaUIHelp.setHelp(fViewer, getHelpContextId()); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ abstract protected String getHelpContextId(); /** * Adds additional listeners to this view. */ protected void hookViewerListeners() { fViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!fProcessSelectionEvents) return; if (JavaBrowsingPreferencePage.openEditorOnSingleClick()) new ShowInEditorAction().run(event.getSelection(), getSite().getPage()); else linkToEditor((IStructuredSelection)event.getSelection()); } }); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (fProcessSelectionEvents && !JavaBrowsingPreferencePage.openEditorOnSingleClick()) new ShowInEditorAction().run(event.getSelection(), getSite().getPage()); } }); } void adjustInputAndSetSelection(IJavaElement je) { je= getSuitableJavaElement(je); IJavaElement elementToSelect= findElementToSelect(je); IJavaElement newInput= findInputForJavaElement(je); if (elementToSelect == null && !isValidInput(newInput)) // Clear input setInput(null); else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) // Adjust input to selection setInput(findInputForJavaElement(je)); if (elementToSelect != null) setSelection(new StructuredSelection(elementToSelect), true); else setSelection(StructuredSelection.EMPTY, true); } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; if (isValidInput(je)) return je; return findInputForJavaElement(je.getParent()); } final protected IJavaElement findElementToSelect(Object obj) { if (obj instanceof IJavaElement) return findElementToSelect((IJavaElement)obj); return null; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ abstract protected IJavaElement findElementToSelect(IJavaElement je); private Object getSingleElementFromSelection(ISelection selection) { if (!(selection instanceof StructuredSelection) || selection.isEmpty()) return null; Iterator iter= ((StructuredSelection)selection).iterator(); Object firstElement= iter.next(); if (!(firstElement instanceof IJavaElement)) return firstElement; Object currentInput= (IJavaElement)getViewer().getInput(); if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaElement)firstElement))) if (iter.hasNext()) // multi selection and view is empty return null; else // ok: single selection and view is empty return firstElement; // be nice to multi selection while (iter.hasNext()) { Object element= iter.next(); if (!(element instanceof IJavaElement)) return null; if (!currentInput.equals(findInputForJavaElement((IJavaElement)element))) return null; } return firstElement; } /** * Gets the typeComparator. * @return Returns a JavaElementTypeComparator */ protected Comparator getTypeComparator() { return fTypeComparator; } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { if (selection == null || selection.isEmpty()) return; Object obj= selection.getFirstElement(); Object element= null; if (selection.size() == 1) { if (obj instanceof IJavaElement) { IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT); if (cu != null) element= getResourceFor(cu); if (element == null) element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE); } else if (obj instanceof IFile) element= obj; if (element == null) return; IWorkbenchPage page= getSite().getPage(); IEditorPart editorArray[]= page.getEditors(); for (int i= 0; i < editorArray.length; ++i) { IEditorPart editor= editorArray[i]; Object input= getElementOfInput(editor.getEditorInput()); if (input != null && input.equals(element)) { page.bringToTop(editor); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(editor, (IJavaElement) obj); return; } } } } private void setSelectionFromEditor(IWorkbenchPart part) { if (part == null) return; IWorkbenchPartSite site= part.getSite(); if (site == null) return; ISelectionProvider provider= site.getSelectionProvider(); if (provider != null) setSelectionFromEditor(part, provider.getSelection()); } private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) { if (part instanceof IEditorPart && JavaBrowsingPreferencePage.linkViewSelectionToEditor()) { IEditorInput ei= ((IEditorPart)part).getEditorInput(); if (selection instanceof ITextSelection) { int offset= ((ITextSelection)selection).getOffset(); IJavaElement element= getElementForInputAt(ei, offset); if (element != null) { adjustInputAndSetSelection(element); return; } } if (ei instanceof IFileEditorInput) { IFile file= ((IFileEditorInput)ei).getFile(); IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class); if (je == null) { setSelection(null, false); return; } adjustInputAndSetSelection(je); } else if (ei instanceof IClassFileEditorInput) { IClassFile cf= ((IClassFileEditorInput)ei).getClassFile(); adjustInputAndSetSelection(cf); } return; } } /** * 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; } private IResource getResourceFor(Object element) { if (element instanceof IJavaElement) { if (element instanceof IWorkingCopy) { IWorkingCopy wc= (IWorkingCopy)element; IJavaElement original= wc.getOriginalElement(); if (original != null) element= original; } try { element= ((IJavaElement)element).getUnderlyingResource(); } catch (JavaModelException e) { return null; } } if (!(element instanceof IResource) || ((IResource)element).isPhantom()) { return null; } return (IResource)element; } private void setSelection(ISelection selection, boolean reveal) { if (selection != null && selection.equals(fViewer.getSelection())) return; fProcessSelectionEvents= false; fViewer.setSelection(selection, reveal); fProcessSelectionEvents= true; } /** * Tries to find the given element in a workingcopy. */ protected static IJavaElement getWorkingCopy(IJavaElement input) { try { if (input instanceof ICompilationUnit) return EditorUtility.getWorkingCopy((ICompilationUnit)input); else return EditorUtility.getWorkingCopy(input, true); } catch (JavaModelException ex) { } return null; } /** * Returns the original element from which the specified working copy * element was created from. This is a handle only method, the * returned element may or may not exist. * * @param workingCopy the element for which to get the original * @return the original Java element or <code>null</code> if this is not a working copy element */ protected static IJavaElement getOriginal(IJavaElement workingCopy) { ICompilationUnit cu= getCompilationUnit(workingCopy); if (cu != null) return ((IWorkingCopy)cu).getOriginal(workingCopy); return null; } /** * Returns the compilation unit for the given java element. * * @param element the java element whose compilation unit is searched for * @return the compilation unit of the given java element */ protected static ICompilationUnit getCompilationUnit(IJavaElement element) { if (element == null) return null; if (element instanceof IMember) return ((IMember) element).getCompilationUnit(); int type= element.getElementType(); if (IJavaElement.COMPILATION_UNIT == type) return (ICompilationUnit) element; if (IJavaElement.CLASS_FILE == type) return null; return getCompilationUnit(element.getParent()); } /** * Converts the given Java element to one which is suitable for this * view. It takes into account wether the view shows working copies or not. * * @param element the Java element to be converted * @return an element suitable for this view */ protected IJavaElement getSuitableJavaElement(Object obj) { if (!(obj instanceof IJavaElement)) return null; IJavaElement element= (IJavaElement)obj; if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0) return element; if (element.getElementType() == IJavaElement.CLASS_FILE) return element; if (((BaseJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy()) { IJavaElement wc= getWorkingCopy(element); if (wc != null) element= wc; return element; } else { ICompilationUnit cu= getCompilationUnit(element); if (cu != null && ((IWorkingCopy)cu).isWorkingCopy()) return ((IWorkingCopy)cu).getOriginal(element); else return element; } } /** * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementForInputAt(IEditorInput input, int offset) { if (input instanceof IClassFileEditorInput) { try { return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset); } catch (JavaModelException ex) { return null; } } IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(input); if (unit != null) synchronized (unit) { try { unit.reconcile(); return unit.getElementAt(offset); } catch (JavaModelException x) { } } return null; } protected IType getTypeForCU(ICompilationUnit cu) { cu= (ICompilationUnit)getSuitableJavaElement(cu); // Use primary type if possible IType primaryType= JavaModelUtil.findPrimaryType(cu); if (primaryType != null) return primaryType; // Use first top-level type try { IType[] types= cu.getTypes(); if (types.length > 0) return types[0]; else return null; } catch (JavaModelException ex) { return null; } } }
13,206
Bug 13206 Missing resource
20020409: Package View>Context Menu>OpenNewWindowAction.text
resolved fixed
5ba0c30
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-04-11T08:34:36Z
2002-04-10T12:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/PatchedOpenInNewWindowAction.java