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
27,636
Bug 27636 Organize Import ordering differs for different VMs
Build 20021203 OrganizeImportTest.testBaseGroups1 failed because the import ordering was different. If fixed the test by looking at the VM version and then do different asserts. However this is just a workaround to make the tests run again. The import order must not depend on the VM version. Please remove the VM version check in the test when this PR is fixed.
verified fixed
b2a1cfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:08:27Z
2002-12-04T11:06:40Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java
27,636
Bug 27636 Organize Import ordering differs for different VMs
Build 20021203 OrganizeImportTest.testBaseGroups1 failed because the import ordering was different. If fixed the test by looking at the VM version and then do different asserts. However this is just a workaround to make the tests run again. The import order must not depend on the VM version. Please remove the VM version check in the test when this PR is fixed.
verified fixed
b2a1cfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:08:27Z
2002-12-04T11:06:40Z
org.eclipse.jdt.ui/core
27,636
Bug 27636 Organize Import ordering differs for different VMs
Build 20021203 OrganizeImportTest.testBaseGroups1 failed because the import ordering was different. If fixed the test by looking at the VM version and then do different asserts. However this is just a workaround to make the tests run again. The import order must not depend on the VM version. Please remove the VM version check in the test when this PR is fixed.
verified fixed
b2a1cfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:08:27Z
2002-12-04T11:06:40Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
31,763
Bug 31763 Java Example Project: Still uses JRE_LIB
20030211 should update the example project
resolved fixed
3619f8e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:36:59Z
2003-02-13T12:40:00Z
org.eclipse.jdt.ui.examples.projects/examples/org/eclipse/jdt/internal/ui/exampleprojects/ExampleProjectCreationWizard.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.exampleprojects; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExecutableExtension; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.ui.dialogs.IOverwriteQuery; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; public class ExampleProjectCreationWizard extends BasicNewResourceWizard implements INewWizard, IExecutableExtension { private ExampleProjectCreationWizardPage[] fPages; private IConfigurationElement fConfigElement; public ExampleProjectCreationWizard() { super(); setDialogSettings(ExampleProjectsPlugin.getDefault().getDialogSettings()); setWindowTitle(ExampleProjectMessages.getString("ExampleProjectCreationWizard.title")); //$NON-NLS-1$ setNeedsProgressMonitor(true); } /* * @see BasicNewResourceWizard#initializeDefaultPageImageDescriptor */ protected void initializeDefaultPageImageDescriptor() { if (fConfigElement != null) { String banner= fConfigElement.getAttribute("banner"); //$NON-NLS-1$ if (banner != null) { ImageDescriptor desc= ExampleProjectsPlugin.getDefault().getImageDescriptor(banner); setDefaultPageImageDescriptor(desc); } } } /* * @see Wizard#addPages */ public void addPages() { super.addPages(); IConfigurationElement[] children = fConfigElement.getChildren("projectsetup"); //$NON-NLS-1$ if (children == null || children.length == 0) { ExampleProjectsPlugin.log("descriptor must contain one ore more projectsetup tags"); //$NON-NLS-1$ return; } fPages= new ExampleProjectCreationWizardPage[children.length]; for (int i= 0; i < children.length; i++) { IConfigurationElement curr= children[i]; fPages[i]= new ExampleProjectCreationWizardPage(i, children[i]); addPage(fPages[i]); } } /* * @see Wizard#performFinish */ public boolean performFinish() { ExampleProjectCreationOperation runnable= new ExampleProjectCreationOperation(fPages, new ImportOverwriteQuery()); IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable); try { getContainer().run(false, true, op); } catch (InvocationTargetException e) { handleException(e.getTargetException()); return false; } catch (InterruptedException e) { return false; } BasicNewProjectResourceWizard.updatePerspective(fConfigElement); IResource res= runnable.getElementToOpen(); if (res != null) { openResource(res); } return true; } private void handleException(Throwable target) { String title= ExampleProjectMessages.getString("ExampleProjectCreationWizard.op_error.title"); //$NON-NLS-1$ String message= ExampleProjectMessages.getString("ExampleProjectCreationWizard.op_error.message"); //$NON-NLS-1$ if (target instanceof CoreException) { IStatus status= ((CoreException)target).getStatus(); ErrorDialog.openError(getShell(), title, message, status); ExampleProjectsPlugin.log(status); } else { MessageDialog.openError(getShell(), title, target.getMessage()); ExampleProjectsPlugin.log(target); } } private void openResource(final IResource resource) { if (resource.getType() != IResource.FILE) { return; } IWorkbenchWindow window= ExampleProjectsPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return; } final IWorkbenchPage activePage= window.getActivePage(); if (activePage != null) { final Display display= getShell().getDisplay(); display.asyncExec(new Runnable() { public void run() { try { activePage.openEditor((IFile)resource); } catch (PartInitException e) { ExampleProjectsPlugin.log(e); } } }); selectAndReveal(resource); } } /** * Stores the configuration element for the wizard. The config element will be used * in <code>performFinish</code> to set the result perspective. */ public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) { fConfigElement= cfig; } // overwrite dialog private class ImportOverwriteQuery implements IOverwriteQuery { public String queryOverwrite(String file) { String[] returnCodes= { YES, NO, ALL, CANCEL}; int returnVal= openDialog(file); return returnVal < 0 ? CANCEL : returnCodes[returnVal]; } private int openDialog(final String file) { final int[] result= { IDialogConstants.CANCEL_ID }; getShell().getDisplay().syncExec(new Runnable() { public void run() { String title= ExampleProjectMessages.getString("ExampleProjectCreationWizard.overwritequery.title"); //$NON-NLS-1$ String msg= ExampleProjectMessages.getFormattedString("ExampleProjectCreationWizard.overwritequery.message", file); //$NON-NLS-1$ String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.CANCEL_LABEL}; MessageDialog dialog= new MessageDialog(getShell(), title, null, msg, MessageDialog.QUESTION, options, 0); result[0]= dialog.open(); } }); return result[0]; } } }
31,999
Bug 31999 Error when opening editor on class file not hosted in a Java project
I20030214 - create Simple project - create a file A.class - open it observe: you get an error saying that Simple doesn't exist.
resolved fixed
406f993
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:57:51Z
2003-02-17T13:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClassFileEditor.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModelStatusConstants; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.util.IClassFileDisassembler; import org.eclipse.jdt.core.util.IClassFileReader; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIStatus; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentDialog; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IMemento; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; /** * Java specific text editor. */ public class ClassFileEditor extends JavaEditor implements ClassFileDocumentProvider.InputChangeListener { /** The horizontal scroll increment. */ private static final int HORIZONTAL_SCROLL_INCREMENT= 10; /** The vertical scroll increment. */ private static final int VERTICAL_SCROLL_INCREMENT= 10; /** * A form to attach source to a class file. */ private class SourceAttachmentForm implements IPropertyChangeListener { private final IClassFile fFile; private ScrolledComposite fScrolledComposite; private Color fBackgroundColor; private Color fForegroundColor; private Color fSeparatorColor; private List fBannerLabels= new ArrayList(); private List fHeaderLabels= new ArrayList(); private Font fFont; /** * Creates a source attachment form for a class file. */ public SourceAttachmentForm(IClassFile file) { fFile= file; } /** * Returns the package fragment root of this file. */ private IPackageFragmentRoot getPackageFragmentRoot(IClassFile file) { IJavaElement element= file.getParent(); while (element != null && element.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) element= element.getParent(); return (IPackageFragmentRoot) element; } /** * Creates the control of the source attachment form. */ public Control createControl(Composite parent) { Display display= parent.getDisplay(); fBackgroundColor= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); fForegroundColor= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND); fSeparatorColor= new Color(display, 152, 170, 203); JFaceResources.getFontRegistry().addListener(this); fScrolledComposite= new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL); fScrolledComposite.setAlwaysShowScrollBars(false); fScrolledComposite.setExpandHorizontal(true); fScrolledComposite.setExpandVertical(true); fScrolledComposite.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { JFaceResources.getFontRegistry().removeListener(SourceAttachmentForm.this); fScrolledComposite= null; fSeparatorColor.dispose(); fSeparatorColor= null; fBannerLabels.clear(); fHeaderLabels.clear(); if (fFont != null) { fFont.dispose(); fFont= null; } } }); fScrolledComposite.addControlListener(new ControlListener() { public void controlMoved(ControlEvent e) {} public void controlResized(ControlEvent e) { Rectangle clientArea = fScrolledComposite.getClientArea(); ScrollBar verticalBar= fScrolledComposite.getVerticalBar(); verticalBar.setIncrement(VERTICAL_SCROLL_INCREMENT); verticalBar.setPageIncrement(clientArea.height - verticalBar.getIncrement()); ScrollBar horizontalBar= fScrolledComposite.getHorizontalBar(); horizontalBar.setIncrement(HORIZONTAL_SCROLL_INCREMENT); horizontalBar.setPageIncrement(clientArea.width - horizontalBar.getIncrement()); } }); Composite composite= createComposite(fScrolledComposite); composite.setLayout(new GridLayout()); createTitleLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.title")); //$NON-NLS-1$ createLabel(composite, null); createLabel(composite, null); createHeadingLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.heading")); //$NON-NLS-1$ Composite separator= createCompositeSeparator(composite); GridData data= new GridData(GridData.FILL_HORIZONTAL); data.heightHint= 2; separator.setLayoutData(data); try { IPackageFragmentRoot root= getPackageFragmentRoot(fFile); if (root != null) { createSourceAttachmentControls(composite, root); } } catch (JavaModelException e) { String title= JavaEditorMessages.getString("SourceAttachmentForm.error.title"); //$NON-NLS-1$ String message= JavaEditorMessages.getString("SourceAttachmentForm.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, fScrolledComposite.getShell(), title, message); } separator= createCompositeSeparator(composite); data= new GridData(GridData.FILL_HORIZONTAL); data.heightHint= 2; separator.setLayoutData(data); StyledText styledText= createCodeView(composite); data= new GridData(GridData.FILL_BOTH); styledText.setLayoutData(data); updateCodeView(styledText, fFile); fScrolledComposite.setContent(composite); fScrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); return fScrolledComposite; } private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root) throws JavaModelException { IClasspathEntry entry= root.getRawClasspathEntry(); IPath containerPath= null; IJavaProject jproject= root.getJavaProject(); if (entry == null || !root.isArchive()) { createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSource", fFile.getElementName())); //$NON-NLS-1$ return; } if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { containerPath= entry.getPath(); entry= SourceAttachmentDialog.getClasspathEntryToEdit(jproject, containerPath, root.getPath()); if (entry == null) { IClasspathContainer container= JavaCore.getClasspathContainer(entry.getPath(), root.getJavaProject()); String containerName= container == null ? entry.getPath().toString() : container.getDescription(); createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.containerEntry", containerName)); //$NON-NLS-1$ return; } } Button button; IPath path= entry.getSourceAttachmentPath(); if (path == null || path.isEmpty()) { createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSourceAttachment", root.getElementName())); //$NON-NLS-1$ createLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.message.pressButtonToAttach")); //$NON-NLS-1$ createLabel(composite, null); button= createButton(composite, JavaEditorMessages.getString("SourceAttachmentForm.button.attachSource")); //$NON-NLS-1$ } else { createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSourceInAttachment", fFile.getElementName())); //$NON-NLS-1$ createLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.message.pressButtonToChange")); //$NON-NLS-1$ createLabel(composite, null); button= createButton(composite, JavaEditorMessages.getString("SourceAttachmentForm.button.changeAttachedSource")); //$NON-NLS-1$ } button.addSelectionListener(getButtonListener(entry, containerPath, jproject)); } private SelectionListener getButtonListener(final IClasspathEntry entry, final IPath containerPath, final IJavaProject jproject) { return new SelectionListener() { public void widgetSelected(SelectionEvent event) { try { SourceAttachmentDialog dialog= new SourceAttachmentDialog(fScrolledComposite.getShell(), entry, containerPath, jproject, true); if (dialog.open() == SourceAttachmentDialog.OK) verifyInput(getEditorInput()); } catch (CoreException e) { String title= JavaEditorMessages.getString("SourceAttachmentForm.error.title"); //$NON-NLS-1$ String message= JavaEditorMessages.getString("SourceAttachmentForm.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, fScrolledComposite.getShell(), title, message); } } public void widgetDefaultSelected(SelectionEvent e) {} }; } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { for (Iterator iterator = fBannerLabels.iterator(); iterator.hasNext();) { Label label = (Label) iterator.next(); label.setFont(JFaceResources.getBannerFont()); } for (Iterator iterator = fHeaderLabels.iterator(); iterator.hasNext();) { Label label = (Label) iterator.next(); label.setFont(JFaceResources.getHeaderFont()); } Control control= fScrolledComposite.getContent(); fScrolledComposite.setMinSize(control.computeSize(SWT.DEFAULT, SWT.DEFAULT)); fScrolledComposite.setContent(control); fScrolledComposite.layout(true); fScrolledComposite.redraw(); } // --- copied from org.eclipse.update.ui.forms.internal.FormWidgetFactory private Composite createComposite(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(fBackgroundColor); // composite.addMouseListener(new MouseAdapter() { // public void mousePressed(MouseEvent e) { // ((Control) e.widget).setFocus(); // } // }); return composite; } private Composite createCompositeSeparator(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(fSeparatorColor); return composite; } private StyledText createCodeView(Composite parent) { int styles= SWT.MULTI | SWT.FULL_SELECTION; StyledText styledText= new StyledText(parent, styles); styledText.setBackground(fBackgroundColor); styledText.setForeground(fForegroundColor); styledText.setEditable(false); return styledText; } private Label createLabel(Composite parent, String text) { Label label = new Label(parent, SWT.NONE); if (text != null) label.setText(text); label.setBackground(fBackgroundColor); label.setForeground(fForegroundColor); return label; } private Label createTitleLabel(Composite parent, String text) { Label label = new Label(parent, SWT.NONE); if (text != null) label.setText(text); label.setBackground(fBackgroundColor); label.setForeground(fForegroundColor); label.setFont(JFaceResources.getHeaderFont()); fHeaderLabels.add(label); return label; } private Label createHeadingLabel(Composite parent, String text) { Label label = new Label(parent, SWT.NONE); if (text != null) label.setText(text); label.setBackground(fBackgroundColor); label.setForeground(fForegroundColor); label.setFont(JFaceResources.getBannerFont()); fBannerLabels.add(label); return label; } private Button createButton(Composite parent, String text) { Button button = new Button(parent, SWT.FLAT); button.setBackground(fBackgroundColor); button.setForeground(fForegroundColor); if (text != null) button.setText(text); // button.addFocusListener(visibilityHandler); return button; } private void updateCodeView(StyledText styledText, IClassFile classFile) { String content= null; int flags= IClassFileReader.FIELD_INFOS | IClassFileReader.METHOD_INFOS | IClassFileReader.SUPER_INTERFACES; IClassFileReader classFileReader= ToolFactory.createDefaultClassFileReader(classFile, flags); if (classFileReader != null) { IClassFileDisassembler disassembler= ToolFactory.createDefaultClassFileDisassembler(); content= disassembler.disassemble(classFileReader, "\n"); //$NON-NLS-1$ } styledText.setText(content == null ? "" : content); //$NON-NLS-1$ } }; private StackLayout fStackLayout; private Composite fParent; private Composite fViewerComposite; private Control fSourceAttachmentForm; /** * Default constructor. */ public ClassFileEditor() { super(); setDocumentProvider(JavaPlugin.getDefault().getClassFileDocumentProvider()); setEditorContextMenuId("#ClassFileEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#ClassFileRulerContext"); //$NON-NLS-1$ setOutlinerContextMenuId("#ClassFileOutlinerContext"); //$NON-NLS-1$ // don't set help contextId, we install our own help context } /* * @see AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); setAction(ITextEditorActionConstants.SAVE, null); setAction(ITextEditorActionConstants.REVERT_TO_SAVED, null); /* * 1GF82PL: ITPJUI:ALL - Need to be able to add bookmark to classfile * * // replace default action with class file specific ones * * setAction(ITextEditorActionConstants.BOOKMARK, new AddClassFileMarkerAction("AddBookmark.", this, IMarker.BOOKMARK, true)); //$NON-NLS-1$ * setAction(ITextEditorActionConstants.ADD_TASK, new AddClassFileMarkerAction("AddTask.", this, IMarker.TASK, false)); //$NON-NLS-1$ * setAction(ITextEditorActionConstants.RULER_MANAGE_BOOKMARKS, new ClassFileMarkerRulerAction("ManageBookmarks.", getVerticalRuler(), this, IMarker.BOOKMARK, true)); //$NON-NLS-1$ * setAction(ITextEditorActionConstants.RULER_MANAGE_TASKS, new ClassFileMarkerRulerAction("ManageTasks.", getVerticalRuler(), this, IMarker.TASK, true)); //$NON-NLS-1$ */ setAction(ITextEditorActionConstants.BOOKMARK, null); setAction(ITextEditorActionConstants.ADD_TASK, null); } /* * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementAt(int offset) { if (getEditorInput() instanceof IClassFileEditorInput) { try { IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput(); return input.getClassFile().getElementAt(offset); } catch (JavaModelException x) { } } return null; } /* * @see JavaEditor#getCorrespondingElement(IJavaElement) */ protected IJavaElement getCorrespondingElement(IJavaElement element) { if (getEditorInput() instanceof IClassFileEditorInput) { IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput(); IJavaElement parent= element.getAncestor(IJavaElement.CLASS_FILE); if (input.getClassFile().equals(parent)) return element; } return null; } /* * @see IEditorPart#saveState(IMemento) */ public void saveState(IMemento memento) { } /* * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) */ protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { if (page != null && input instanceof IClassFileEditorInput) { IClassFileEditorInput cfi= (IClassFileEditorInput) input; page.setInput(cfi.getClassFile()); } } /* * 1GEPKT5: ITPJUI:Linux - Source in editor for external classes is editable * Removed methods isSaveOnClosedNeeded and isDirty. * Added method isEditable. */ /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#isEditable() */ public boolean isEditable() { return false; } /** * Translates the given editor input into an <code>ExternalClassFileEditorInput</code> * if it is a file editor input representing an external class file. * * @param input the editor input to be transformed if necessary * @return the transformed editor input */ protected IEditorInput transformEditorInput(IEditorInput input) { if (input instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) input).getFile(); IClassFileEditorInput classFileInput= new ExternalClassFileEditorInput(file); if (classFileInput.getClassFile() != null) input= classFileInput; } return input; } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { input= transformEditorInput(input); if (!(input instanceof IClassFileEditorInput)) throw new CoreException(JavaUIStatus.createError( IJavaModelStatusConstants.INVALID_RESOURCE_TYPE, JavaEditorMessages.getString("ClassFileEditor.error.invalid_input_message"), //$NON-NLS-1$ null)); //$NON-NLS-1$ JavaModelException e= probeInputForSource(input); if (e != null) { IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input; IClassFile file= classFileEditorInput.getClassFile(); if (!file.getJavaProject().isOnClasspath(file)) { throw new CoreException(JavaUIStatus.createError( IJavaModelStatusConstants.INVALID_RESOURCE, JavaEditorMessages.getString("ClassFileEditor.error.classfile_not_on_classpath"), //$NON-NLS-1$ null)); //$NON-NLS-1$ } else { throw e; } } IDocumentProvider documentProvider= getDocumentProvider(); if (documentProvider instanceof ClassFileDocumentProvider) ((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this); super.doSetInput(input); documentProvider= getDocumentProvider(); if (documentProvider instanceof ClassFileDocumentProvider) ((ClassFileDocumentProvider) documentProvider).addInputChangeListener(this); verifyInput(getEditorInput()); } /* * @see IWorkbenchPart#createPartControl(Composite) */ public void createPartControl(Composite parent) { fParent= new Composite(parent, SWT.NONE); fStackLayout= new StackLayout(); fParent.setLayout(fStackLayout); fViewerComposite= new Composite(fParent, SWT.NONE); fViewerComposite.setLayout(new FillLayout()); super.createPartControl(fViewerComposite); fStackLayout.topControl= fViewerComposite; fParent.layout(); try { verifyInput(getEditorInput()); } catch (CoreException e) { String title= JavaEditorMessages.getString("ClassFileEditor.error.title"); //$NON-NLS-1$ String message= JavaEditorMessages.getString("ClassFileEditor.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, fParent.getShell(), title, message); } } private JavaModelException probeInputForSource(IEditorInput input) { if (input == null) return null; IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input; IClassFile file= classFileEditorInput.getClassFile(); try { file.getSourceRange(); } catch (JavaModelException e) { return e; } return null; } /** * Checks if the class file input has no source attached. If so, a source attachment form is shown. */ private void verifyInput(IEditorInput input) throws CoreException { if (fParent == null || input == null) return; IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input; IClassFile file= classFileEditorInput.getClassFile(); // show source attachment form if no source found if (file.getSourceRange() == null) { // dispose old source attachment form if (fSourceAttachmentForm != null) fSourceAttachmentForm.dispose(); SourceAttachmentForm form= new SourceAttachmentForm(file); fSourceAttachmentForm= form.createControl(fParent); fStackLayout.topControl= fSourceAttachmentForm; fParent.layout(); // show source viewer } else { if (fSourceAttachmentForm != null) { fSourceAttachmentForm.dispose(); fSourceAttachmentForm= null; fStackLayout.topControl= fViewerComposite; fParent.layout(); } } } /* * @see ClassFileDocumentProvider.InputChangeListener#inputChanged(IClassFileEditorInput) */ public void inputChanged(final IClassFileEditorInput input) { if (input != null && input.equals(getEditorInput())) { ISourceViewer viewer= getSourceViewer(); if (viewer != null) { StyledText textWidget= viewer.getTextWidget(); if (textWidget != null && !textWidget.isDisposed()) { textWidget.getDisplay().asyncExec(new Runnable() { public void run() { setInput(input); } }); } } } } /* * @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return new SourceViewer(parent, ruler, styles) { public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester); } }; } /* * @see org.eclipse.ui.IWorkbenchPart#dispose() */ public void dispose() { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18510 IDocumentProvider documentProvider= getDocumentProvider(); if (documentProvider instanceof ClassFileDocumentProvider) ((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this); super.dispose(); } /* * @see org.eclipse.ui.IWorkbenchPart#setFocus() */ public void setFocus() { super.setFocus(); if (fSourceAttachmentForm != null && !fSourceAttachmentForm.isDisposed()) fSourceAttachmentForm.setFocus(); } }
32,033
Bug 32033 Spaces for TAB preference is confusing
null
resolved fixed
257ef56
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T09:32:47Z
2003-02-17T16:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import java.util.Iterator; import java.util.NoSuchElementException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; /** * Auto indent strategy sensitive to brackets. */ public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy { private final static String COMMENT= "//"; //$NON-NLS-1$ private int fTabWidth= -1; private Boolean fUseSpaces= null; public JavaAutoIndentStrategy() { } // evaluate the line with the opening bracket that matches the closing bracket on the given line protected int findMatchingOpenBracket(IDocument d, int line, int end, int closingBracketIncrease) throws BadLocationException { int start= d.getLineOffset(line); int brackcount= getBracketCount(d, start, end, false) - closingBracketIncrease; // sum up the brackets counts of each line (closing brackets count negative, // opening positive) until we find a line the brings the count to zero while (brackcount < 0) { line--; if (line < 0) { return -1; } start= d.getLineOffset(line); end= start + d.getLineLength(line) - 1; brackcount += getBracketCount(d, start, end, false); } return line; } private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException { int bracketcount= 0; while (start < end) { char curr= d.getChar(start); start++; switch (curr) { case '/' : if (start < end) { char next= d.getChar(start); if (next == '*') { // a comment starts, advance to the comment end start= getCommentEnd(d, start + 1, end); } else if (next == '/') { // '//'-comment: nothing to do anymore on this line start= end; } } break; case '*' : if (start < end) { char next= d.getChar(start); if (next == '/') { // we have been in a comment: forget what we read before bracketcount= 0; start++; } } break; case '{' : bracketcount++; ignoreCloseBrackets= false; break; case '}' : if (!ignoreCloseBrackets) { bracketcount--; } break; case '"' : case '\'' : start= getStringEnd(d, start, end, curr); break; default : } } return bracketcount; } // ----------- bracket counting ------------------------------------------------------ private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '*') { if (pos < end && d.getChar(pos) == '/') { return pos + 1; } } } return end; } protected String getIndentOfLine(IDocument d, int line) throws BadLocationException { if (line > -1) { int start= d.getLineOffset(line); int end= start + d.getLineLength(line) - 1; int whiteend= findEndOfWhiteSpace(d, start, end); return d.get(start, whiteend - start); } else { return ""; //$NON-NLS-1$ } } private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '\\') { // ignore escaped characters pos++; } else if (curr == ch) { return pos; } } return end; } protected void smartInsertAfterBracket(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); int start= d.getLineOffset(line); int whiteend= findEndOfWhiteSpace(d, start, c.offset); // shift only when line does not contain any text up to the closing bracket if (whiteend == c.offset) { // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1 && indLine != line) { // take the indent of the found line StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine)); // add the rest of the current line including the just added close bracket replaceText.append(d.get(whiteend, c.offset - whiteend)); replaceText.append(c.text); // modify document command c.length += c.offset - start; c.offset= start; c.text= replaceText.toString(); } } } catch (BadLocationException e) { JavaPlugin.log(e); } } protected void smartIndentAfterNewLine(IDocument d, DocumentCommand c) { int docLength= d.getLength(); if (c.offset == -1 || docLength == 0) return; try { int p= (c.offset == docLength ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); StringBuffer buf= new StringBuffer(c.text); if (c.offset < docLength && d.getChar(c.offset) == '}') { int indLine= findMatchingOpenBracket(d, line, c.offset, 0); if (indLine == -1) { indLine= line; } buf.append(getIndentOfLine(d, indLine)); } else { int start= d.getLineOffset(line); // if line just ended a javadoc comment, take the indent from the comment's begin line IDocumentPartitioner partitioner= d.getDocumentPartitioner(); if (partitioner != null) { ITypedRegion region= partitioner.getPartition(start); if (JavaPartitionScanner.JAVA_DOC.equals(region.getType())) start= d.getLineInformationOfOffset(region.getOffset()).getOffset(); } int whiteend= findEndOfWhiteSpace(d, start, c.offset); buf.append(d.get(start, whiteend - start)); if (getBracketCount(d, start, c.offset, true) > 0) { buf.append(createIndent(1, useSpaces())); } } c.text= buf.toString(); } catch (BadLocationException e) { JavaPlugin.log(e); } } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { JavaPlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } private static boolean startsWithClosingBrace(String string) { final int length= string.length(); int i= 0; while (i != length && Character.isWhitespace(string.charAt(i))) ++i; if (i == length) return false; return string.charAt(i) == '}'; } protected void smartPaste(IDocument document, DocumentCommand command) { String lineDelimiter= getLineDelimiter(document); try { String pastedText= command.text; Assert.isNotNull(pastedText); Assert.isTrue(pastedText.length() > 1); // extend selection begin if only whitespaces int selectionStart= command.offset; IRegion region= document.getLineInformationOfOffset(selectionStart); String notSelected= document.get(region.getOffset(), selectionStart - region.getOffset()); String selected= document.get(selectionStart, region.getOffset() + region.getLength() - selectionStart); if (notSelected.trim().length() == 0 && selected.trim().length() != 0) { pastedText= notSelected + pastedText; command.length += notSelected.length(); command.offset= region.getOffset(); } // choose smaller indent of block and preceeding non-empty line String blockIndent= getBlockIndent(document, command); String insideBlockIndent= blockIndent == null ? "" : blockIndent + createIndent(1, useSpaces()); //$NON-NLS-1$ // add one indent level int insideBlockIndentSize= calculateDisplayedWidth(insideBlockIndent, getTabWidth()); int previousIndentSize= getIndentSize(document, command); int newIndentSize= insideBlockIndentSize < previousIndentSize ? insideBlockIndentSize : previousIndentSize; // indent is different if block starts with '}' if (startsWithClosingBrace(pastedText)) { int outsideBlockIndentSize= blockIndent == null ? 0 : calculateDisplayedWidth(blockIndent, getTabWidth()); newIndentSize = outsideBlockIndentSize; } // check selection int offset= command.offset; int line= document.getLineOfOffset(offset); int lineOffset= document.getLineOffset(line); String prefix= document.get(lineOffset, offset - lineOffset); boolean formatFirstLine= prefix.trim().length() == 0; String formattedParagraph= format(pastedText, newIndentSize, lineDelimiter, formatFirstLine); // paste if (formatFirstLine) { int end= command.offset + command.length; command.offset= lineOffset; command.length= end - command.offset; } command.text= formattedParagraph; } catch (BadLocationException e) { JavaPlugin.log(e); } } private static String getIndentOfLine(String line) { int i= 0; for (; i < line.length(); i++) { if (! Character.isWhitespace(line.charAt(i))) break; } return line.substring(0, i); } /** * Returns the indent of the first non empty line. * A line is considered empty if it only consists of whitespaces or if it * begins with a single line comment followed by whitespaces only. */ private static int getIndentSizeOfFirstLine(String paragraph, boolean includeFirstLine, int tabWidth) { for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { final String line= (String) iterator.next(); if (!includeFirstLine) { includeFirstLine= true; continue; } String indent= null; if (line.startsWith(COMMENT)) { String commentedLine= line.substring(2); // line is empty if (commentedLine.trim().length() == 0) continue; indent= COMMENT + getIndentOfLine(commentedLine); } else { // line is empty if (line.trim().length() == 0) continue; indent= getIndentOfLine(line); } return calculateDisplayedWidth(indent, tabWidth); } return 0; } /** * Returns the minimal indent size of all non empty lines; */ private static int getMinimalIndentSize(String paragraph, boolean includeFirstLine, int tabWidth) { int minIndentSize= Integer.MAX_VALUE; for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { final String line= (String) iterator.next(); if (!includeFirstLine) { includeFirstLine= true; continue; } String indent= null; if (line.startsWith(COMMENT)) { String commentedLine= line.substring(2); // line is empty if (commentedLine.trim().length() == 0) continue; indent= COMMENT + getIndentOfLine(commentedLine); } else { // line is empty if (line.trim().length() == 0) continue; indent=getIndentOfLine(line); } final int indentSize= calculateDisplayedWidth(indent, tabWidth); if (indentSize < minIndentSize) minIndentSize= indentSize; } return minIndentSize == Integer.MAX_VALUE ? 0 : minIndentSize; } /** * Returns the displayed width of a string, taking in account the displayed tab width. * The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string, int tabWidth) { int column= 0; for (int i= 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else column++; return column; } private static boolean isLineEmpty(IDocument document, int line) throws BadLocationException { IRegion region= document.getLineInformation(line); String string= document.get(region.getOffset(), region.getLength()); return string.trim().length() == 0; } private int getIndentSize(IDocument document, DocumentCommand command) { StringBuffer buffer= new StringBuffer(); int docLength= document.getLength(); if (command.offset == -1 || docLength == 0) return 0; try { int p= (command.offset == docLength ? command.offset - 1 : command.offset); int line= document.getLineOfOffset(p); IRegion region= document.getLineInformation(line); String string= document.get(region.getOffset(), command.offset - region.getOffset()); if (line != 0 && string.trim().length() == 0) --line; while (line != 0 && isLineEmpty(document, line)) --line; int start= document.getLineOffset(line); // if line is at end of a javadoc comment, take the indent from the comment's begin line IDocumentPartitioner partitioner= document.getDocumentPartitioner(); if (partitioner != null) { ITypedRegion typedRegion= partitioner.getPartition(start); if (JavaPartitionScanner.JAVA_DOC.equals(typedRegion.getType())) start= document.getLineInformationOfOffset(typedRegion.getOffset()).getOffset(); else if (JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT.equals(typedRegion.getType())) { buffer.append(COMMENT); start += 2; } } int whiteend= findEndOfWhiteSpace(document, start, command.offset); buffer.append(document.get(start, whiteend - start)); if (getBracketCount(document, start, command.offset, true) > 0) { buffer.append(createIndent(1, useSpaces())); } } catch (BadLocationException e) { JavaPlugin.log(e); } return calculateDisplayedWidth(buffer.toString(), getTabWidth()); } private String getBlockIndent(IDocument d, DocumentCommand c) { if (c.offset < 0 || d.getLength() == 0) return null; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1) // take the indent of the found line return getIndentOfLine(d, indLine); } catch (BadLocationException e) { JavaPlugin.log(e); } return null; } private static final class LineIterator implements Iterator { /** The document to iterator over. */ private final IDocument fDocument; /** The line index. */ private int fLineIndex; /** * Creates a line iterator. */ public LineIterator(String string) { fDocument= new Document(string); } /* * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return fLineIndex != fDocument.getNumberOfLines(); } /* * @see java.util.Iterator#next() */ public Object next() { try { IRegion region= fDocument.getLineInformation(fLineIndex++); return fDocument.get(region.getOffset(), region.getLength()); } catch (BadLocationException e) { JavaPlugin.log(e); throw new NoSuchElementException(); } } /* * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } private String createIndent(int level, boolean useSpaces) { StringBuffer buffer= new StringBuffer(); if (useSpaces) { // Fix for bug 29909 contributed by Nikolay Metchev int width= level * getTabWidth(); for (int i= 0; i != width; ++i) buffer.append(' '); } else { for (int i= 0; i != level; ++i) buffer.append('\t'); } return buffer.toString(); } /** * Extends the string to match displayed width. * String is either the empty string or "//" and should not contain whites. */ private static String changePrefix(String string, int displayedWidth, boolean useSpaces, int tabWidth) { // assumption: string contains no whitspaces final StringBuffer buffer= new StringBuffer(string); int column= calculateDisplayedWidth(buffer.toString(), tabWidth); if (column > displayedWidth) return string; if (useSpaces) { while (column != displayedWidth) { buffer.append(' '); ++column; } } else { while (column != displayedWidth) { if (column + tabWidth - (column % tabWidth) <= displayedWidth) { buffer.append('\t'); column += tabWidth - (column % tabWidth); } else { buffer.append(' '); ++column; } } } return buffer.toString(); } /** * Formats a paragraph such that the first non-empty line of the paragraph * will have an indent of size newIndentSize. */ private String format(String paragraph, int newIndentSize, String lineDelimiter, boolean indentFirstLine) { final int tabWidth= getTabWidth(); final int firstLineIndentSize= getIndentSizeOfFirstLine(paragraph, indentFirstLine, tabWidth); final int minIndentSize= getMinimalIndentSize(paragraph, indentFirstLine, tabWidth); if (newIndentSize < firstLineIndentSize - minIndentSize) newIndentSize= firstLineIndentSize - minIndentSize; final StringBuffer buffer= new StringBuffer(); for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); if (indentFirstLine) { String lineIndent= null; if (line.startsWith(COMMENT)) lineIndent= COMMENT + getIndentOfLine(line.substring(2)); else lineIndent= getIndentOfLine(line); String lineContent= line.substring(lineIndent.length()); if (lineContent.length() == 0) { // line was empty; insert as is buffer.append(line); } else { int indentSize= calculateDisplayedWidth(lineIndent, tabWidth); int deltaSize= newIndentSize - firstLineIndentSize; lineIndent= changePrefix(lineIndent.trim(), indentSize + deltaSize, useSpaces(), tabWidth); buffer.append(lineIndent); buffer.append(lineContent); } } else { indentFirstLine= true; buffer.append(line); } if (iterator.hasNext()) buffer.append(lineDelimiter); } return buffer.toString(); } private boolean equalsDelimiter(IDocument d, String txt) { String[] delimiters= d.getLegalLineDelimiters(); for (int i= 0; i < delimiters.length; i++) { if (txt.equals(delimiters[i])) return true; } return false; } private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) { if (command.text.charAt(0) == '}') smartInsertAfterBracket(document, command); } /* * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand(IDocument d, DocumentCommand c) { if (c.length == 0 && c.text != null && equalsDelimiter(d, c.text)) smartIndentAfterNewLine(d, c); else if (c.text.length() == 1) smartIndentAfterBlockDelimiter(d, c); else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE)) smartPaste(d, c); clearCachedValues(); } private static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } private boolean useSpaces() { if (fUseSpaces == null) fUseSpaces= new Boolean(JavaCore.SPACE.equals(JavaCore.getOptions().get(JavaCore.FORMATTER_TAB_CHAR))); return fUseSpaces.booleanValue(); } private int getTabWidth() { if (fTabWidth == -1) // Fix for bug 29909 contributed by Nikolay Metchev fTabWidth= Integer.parseInt(((String)JavaCore.getOptions().get(JavaCore.FORMATTER_TAB_SIZE))); return fTabWidth; } private void clearCachedValues() { fTabWidth= -1; fUseSpaces= null; } }
31,328
Bug 31328 hover key modifier text field: selection is not replaced by new modifier
- given text: Ctrl - select text: Ctrl - press: Shift -> result: Ctrl + Shift expected: Shift (the same holds for the key modifier text field of 'hyperlink style navigation', please fix it too or reassign the bug to me once it is fixed for the hovers pref. page)
resolved fixed
a286ee9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T11:36:37Z
2003-02-07T17:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.HashMap; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.text.Assert; import org.eclipse.swt.SWT; 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.FontMetrics; import org.eclipse.swt.graphics.GC; 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.List; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor; /** * Configures Java Editor hover preferences. * * @since 2.1 */ class JavaEditorHoverConfigurationBlock { // Data structure to hold the values which are edited by the user private static class HoverConfig { private String fModifierString; private boolean fIsEnabled; private int fStateMask; private HoverConfig(String modifier, int stateMask, boolean enabled) { fModifierString= modifier; fIsEnabled= enabled; fStateMask= stateMask; } } private IPreferenceStore fStore; private HoverConfig[] fHoverConfigs; private Text fModifierEditor; private Button fEnableField; private List fHoverList; private Text fDescription; private JavaEditorPreferencePage fMainPreferencePage; private StatusInfo fStatus; public JavaEditorHoverConfigurationBlock(JavaEditorPreferencePage mainPreferencePage, IPreferenceStore store) { Assert.isNotNull(mainPreferencePage); Assert.isNotNull(store); fMainPreferencePage= mainPreferencePage; fStore= store; } /** * Creates page for hover preferences. */ public Control createControl(Composite parent) { Composite hoverComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; hoverComposite.setLayout(layout); GridData gd= new GridData(GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); hoverComposite.setLayoutData(gd); Label label= new Label(hoverComposite, SWT.NONE); label.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.hoverPreferences")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; label.setLayoutData(gd); gd= new GridData(GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); // Hover list fHoverList= new List(hoverComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(parent, 10); fHoverList.setLayoutData(gd); fHoverList.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { handleHoverListSelection(); } public void widgetDefaultSelected(SelectionEvent e) { } }); Composite stylesComposite= new Composite(hoverComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); gd= new GridData(GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(parent, 10) + (2 * fHoverList.getBorderWidth()); stylesComposite.setLayoutData(gd); // Enabled checkbox fEnableField= new Button(stylesComposite, SWT.CHECK); fEnableField.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.enabled")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fEnableField.setLayoutData(gd); fEnableField.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { int i= fHoverList.getSelectionIndex(); boolean state= fEnableField.getSelection(); fModifierEditor.setEnabled(state); fHoverConfigs[i].fIsEnabled= state; handleModifierModified(); } public void widgetDefaultSelected(SelectionEvent e) { } }); // Text field for modifier string label= new Label(stylesComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.keyModifier")); //$NON-NLS-1$ fModifierEditor= new Text(stylesComposite, SWT.BORDER); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); fModifierEditor.setLayoutData(gd); fModifierEditor.addKeyListener(new KeyListener() { private boolean isModifierCandidate; public void keyPressed(KeyEvent e) { isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0; } public void keyReleased(KeyEvent e) { if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { String text= fModifierEditor.getText(); if (text.length() > 0) text= PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.appendModifier", new String[] {text, Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else text= Action.findModifierString(e.stateMask); fModifierEditor.setText(text); fModifierEditor.setSelection(text.length(), text.length()); } } }); fModifierEditor.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleModifierModified(); } }); // Description Label descriptionLabel= new Label(stylesComposite, SWT.LEFT); descriptionLabel.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.description")); //$NON-NLS-1$ gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING); gd.horizontalSpan= 2; descriptionLabel.setLayoutData(gd); fDescription= new Text(stylesComposite, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.horizontalSpan= 2; fDescription.setLayoutData(gd); initialize(); return hoverComposite; } private JavaEditorTextHoverDescriptor[] getContributedHovers() { return JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors(); } void initialize() { JavaEditorTextHoverDescriptor[] hoverDescs= getContributedHovers(); fHoverConfigs= new HoverConfig[hoverDescs.length]; for (int i= 0; i < hoverDescs.length; i++) { fHoverConfigs[i]= new HoverConfig(hoverDescs[i].getModifierString(), hoverDescs[i].getStateMask(), hoverDescs[i].isEnabled()); fHoverList.add(hoverDescs[i].getLabel()); } initializeFields(); } void initializeFields() { fHoverList.getDisplay().asyncExec(new Runnable() { public void run() { if (fHoverList != null && !fHoverList.isDisposed()) { fHoverList.select(0); handleHoverListSelection(); } } }); } void performOk() { StringBuffer buf= new StringBuffer(); for (int i= 0; i < fHoverConfigs.length; i++) { buf.append(getContributedHovers()[i].getId()); buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); if (!fHoverConfigs[i].fIsEnabled) buf.append(JavaEditorTextHoverDescriptor.DISABLED_TAG); String modifier= fHoverConfigs[i].fModifierString; if (modifier == null || modifier.length() == 0) modifier= JavaEditorTextHoverDescriptor.NO_MODIFIER; buf.append(modifier); buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); } fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, buf.toString()); JavaPlugin.getDefault().resetJavaEditorTextHoverDescriptors(); } void performDefaults() { restoreFromPreferences(); initializeFields(); } private void restoreFromPreferences() { String compiledTextHoverModifiers= fStore.getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); StringTokenizer tokenizer= new StringTokenizer(compiledTextHoverModifiers, JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); HashMap idToModifier= new HashMap(tokenizer.countTokens() / 2); while (tokenizer.hasMoreTokens()) { String id= tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) idToModifier.put(id, tokenizer.nextToken()); } for (int i= 0; i < fHoverConfigs.length; i++) { String modifierString= (String)idToModifier.get(getContributedHovers()[i].getId()); boolean enabled= true; if (modifierString == null) modifierString= JavaEditorTextHoverDescriptor.DISABLED_TAG; if (modifierString.startsWith(JavaEditorTextHoverDescriptor.DISABLED_TAG)) { enabled= false; modifierString= modifierString.substring(1); } if (modifierString.equals(JavaEditorTextHoverDescriptor.NO_MODIFIER)) modifierString= ""; //$NON-NLS-1$ fHoverConfigs[i].fModifierString= modifierString; fHoverConfigs[i].fIsEnabled= enabled; fHoverConfigs[i].fStateMask= JavaEditorTextHoverDescriptor.computeStateMask(modifierString); } } private void handleModifierModified() { int i= fHoverList.getSelectionIndex(); String modifiers= fModifierEditor.getText(); fHoverConfigs[i].fModifierString= modifiers; fHoverConfigs[i].fStateMask= JavaEditorTextHoverDescriptor.computeStateMask(modifiers); if (fHoverConfigs[i].fIsEnabled && fHoverConfigs[i].fStateMask == -1) fStatus= new StatusInfo(StatusInfo.ERROR, PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.modifierIsNotValid", fHoverConfigs[i].fModifierString)); //$NON-NLS-1$ else fStatus= new StatusInfo(); updateStatus(); } private void handleHoverListSelection() { int i= fHoverList.getSelectionIndex(); boolean enabled= fHoverConfigs[i].fIsEnabled; fEnableField.setSelection(enabled); fModifierEditor.setEnabled(enabled); fModifierEditor.setText(fHoverConfigs[i].fModifierString); String description= getContributedHovers()[i].getDescription(); if (description == null) description= ""; //$NON-NLS-1$ fDescription.setText(description); } private int convertHeightInCharsToPixels(Control control, int chars) { GC gc = new GC(control); gc.setFont(control.getFont()); FontMetrics fontMetrics = gc.getFontMetrics(); gc.dispose(); if (fontMetrics == null) return 0; return Dialog.convertHeightInCharsToPixels(fontMetrics, chars); } IStatus getStatus() { if (fStatus == null) fStatus= new StatusInfo(); return fStatus; } private void updateStatus() { int i= 0; HashMap stateMasks= new HashMap(fHoverConfigs.length); while (fStatus.isOK() && i < fHoverConfigs.length) { if (fHoverConfigs[i].fIsEnabled) { String label= getContributedHovers()[i].getLabel(); Integer stateMask= new Integer(fHoverConfigs[i].fStateMask); if (fHoverConfigs[i].fStateMask == -1) fStatus= new StatusInfo(StatusInfo.ERROR, PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.modifierIsNotValidForHover", new String[] {fHoverConfigs[i].fModifierString, label})); //$NON-NLS-1$ else if (stateMasks.containsKey(stateMask)) fStatus= new StatusInfo(StatusInfo.ERROR, PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.JavaEditorHoverConfigurationBlock.duplicateModifier", new String[] {label, (String)stateMasks.get(stateMask)})); //$NON-NLS-1$ else stateMasks.put(stateMask, label); } i++; } if (fStatus.isOK()) fMainPreferencePage.updateStatus(fStatus); else { fMainPreferencePage.setValid(false); StatusUtil.applyToStatusLine(fMainPreferencePage, fStatus); } } }
31,302
Bug 31302 Push Down activation issues
first issue: - open a java editor - select the name of a method in the method declaration - invoke "Push Down" -> dialog opens, the selected method is checked but not selected -> It should be selected and revealed. second issue: - open java editor - remove any selection - invoke "Push Down" from the tool bar menu -> you are asked to select a method or field first -> the action only needs to know the type of which methods should be pushed down in order to populate the dialog rather than any concrete method
resolved fixed
4fb9a44
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T14:57:13Z
2003-02-07T15:00:00Z
org.eclipse.jdt.ui/ui
31,302
Bug 31302 Push Down activation issues
first issue: - open a java editor - select the name of a method in the method declaration - invoke "Push Down" -> dialog opens, the selected method is checked but not selected -> It should be selected and revealed. second issue: - open java editor - remove any selection - invoke "Push Down" from the tool bar menu -> you are asked to select a method or field first -> the action only needs to know the type of which methods should be pushed down in order to populate the dialog rather than any concrete method
resolved fixed
4fb9a44
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T14:57:13Z
2003-02-07T15:00:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/PullUpInputPage1.java
31,302
Bug 31302 Push Down activation issues
first issue: - open a java editor - select the name of a method in the method declaration - invoke "Push Down" -> dialog opens, the selected method is checked but not selected -> It should be selected and revealed. second issue: - open java editor - remove any selection - invoke "Push Down" from the tool bar menu -> you are asked to select a method or field first -> the action only needs to know the type of which methods should be pushed down in order to populate the dialog rather than any concrete method
resolved fixed
4fb9a44
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T14:57:13Z
2003-02-07T15:00:00Z
org.eclipse.jdt.ui/ui
31,302
Bug 31302 Push Down activation issues
first issue: - open a java editor - select the name of a method in the method declaration - invoke "Push Down" -> dialog opens, the selected method is checked but not selected -> It should be selected and revealed. second issue: - open java editor - remove any selection - invoke "Push Down" from the tool bar menu -> you are asked to select a method or field first -> the action only needs to know the type of which methods should be pushed down in order to populate the dialog rather than any concrete method
resolved fixed
4fb9a44
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T14:57:13Z
2003-02-07T15:00:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/PushDownInputPage.java
31,237
Bug 31237 FileNotFoundException on exporting templates if file is read-only
20030206 try exporting templates if the file already exists and is read-only not sure here, maybe it's ok to log this exception !MESSAGE Error occurred while writing templates. !STACK 0 java.io.FileNotFoundException: C:\Documents and Settings\akiezun\Desktop\codetemplates.xml (Access is denied) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:102) at java.io.FileOutputStream.<init>(FileOutputStream.java:62) at java.io.FileOutputStream.<init>(FileOutputStream.java:132) at org.eclipse.jdt.internal.corext.template.TemplateSet.saveToFile (TemplateSet.java:178) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.export (CodeTemplateBlock.java:411) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.export (CodeTemplateBlock.java:388) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.doButtonPressed (CodeTemplateBlock.java:336) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock$CodeTemplateAdapter.cu stomButtonPressed(CodeTemplateBlock.java:67) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPress ed(TreeListDialogField.java:165) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSel ected(TreeListDialogField.java:380) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.access$2 (TreeListDialogField.java:376) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSel ected(TreeListDialogField.java:343) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
3ad48aa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T15:12:50Z
2003-02-07T12:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TemplatePreferencePage.java
package org.eclipse.jdt.internal.ui.preferences; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplateSet; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContextType; import org.eclipse.jdt.internal.corext.template.java.JavaDocContextType; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.template.TemplateContentProvider; import org.eclipse.jdt.internal.ui.util.SWTUtil; public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { Template template = (Template) element; switch (columnIndex) { case 0: return template.getName(); case 1: return template.getContextTypeName(); case 2: return template.getDescription(); default: return ""; //$NON-NLS-1$ } } } // preference store keys private static final String PREF_FORMAT_TEMPLATES= PreferenceConstants.TEMPLATES_USE_CODEFORMATTER; private final String[] CONTEXTS= new String[] { JavaContextType.NAME, JavaDocContextType.NAME }; private Templates fTemplates; private CheckboxTableViewer fTableViewer; private Button fAddButton; private Button fEditButton; private Button fImportButton; private Button fExportButton; private Button fExportAllButton; private Button fRemoveButton; private Button fEnableAllButton; private Button fDisableAllButton; private SourceViewer fPatternViewer; private Button fFormatButton; public TemplatePreferencePage() { super(); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(TemplateMessages.getString("TemplatePreferencePage.message")); //$NON-NLS-1$ fTemplates= Templates.getInstance(); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite ancestor) { Composite parent= new Composite(ancestor, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; parent.setLayout(layout); Composite innerParent= new Composite(parent, SWT.NONE); GridLayout innerLayout= new GridLayout(); innerLayout.numColumns= 2; innerLayout.marginHeight= 0; innerLayout.marginWidth= 0; innerParent.setLayout(innerLayout); GridData gd= new GridData(GridData.FILL_BOTH); gd.horizontalSpan= 2; innerParent.setLayoutData(gd); Table table= new Table(innerParent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(3); data.heightHint= convertHeightInCharsToPixels(10); table.setLayoutData(data); table.setHeaderVisible(true); table.setLinesVisible(true); TableLayout tableLayout= new TableLayout(); table.setLayout(tableLayout); TableColumn column1= new TableColumn(table, SWT.NONE); column1.setText(TemplateMessages.getString("TemplatePreferencePage.column.name")); //$NON-NLS-1$ TableColumn column2= new TableColumn(table, SWT.NONE); column2.setText(TemplateMessages.getString("TemplatePreferencePage.column.context")); //$NON-NLS-1$ TableColumn column3= new TableColumn(table, SWT.NONE); column3.setText(TemplateMessages.getString("TemplatePreferencePage.column.description")); //$NON-NLS-1$ fTableViewer= new CheckboxTableViewer(table); fTableViewer.setLabelProvider(new TemplateLabelProvider()); fTableViewer.setContentProvider(new TemplateContentProvider()); fTableViewer.setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object object1, Object object2) { if ((object1 instanceof Template) && (object2 instanceof Template)) { Template left= (Template) object1; Template right= (Template) object2; int result= left.getName().compareToIgnoreCase(right.getName()); if (result != 0) return result; return left.getDescription().compareToIgnoreCase(right.getDescription()); } return super.compare(viewer, object1, object2); } public boolean isSorterProperty(Object element, String property) { return true; } }); fTableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent e) { edit(); } }); fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent e) { selectionChanged1(); } }); fTableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { Template template= (Template) event.getElement(); template.setEnabled(event.getChecked()); } }); Composite buttons= new Composite(innerParent, SWT.NONE); buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; buttons.setLayout(layout); fAddButton= new Button(buttons, SWT.PUSH); fAddButton.setText(TemplateMessages.getString("TemplatePreferencePage.new")); //$NON-NLS-1$ fAddButton.setLayoutData(getButtonGridData(fAddButton)); fAddButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { add(); } }); fEditButton= new Button(buttons, SWT.PUSH); fEditButton.setText(TemplateMessages.getString("TemplatePreferencePage.edit")); //$NON-NLS-1$ fEditButton.setLayoutData(getButtonGridData(fEditButton)); fEditButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { edit(); } }); fRemoveButton= new Button(buttons, SWT.PUSH); fRemoveButton.setText(TemplateMessages.getString("TemplatePreferencePage.remove")); //$NON-NLS-1$ fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton)); fRemoveButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { remove(); } }); fImportButton= new Button(buttons, SWT.PUSH); fImportButton.setText(TemplateMessages.getString("TemplatePreferencePage.import")); //$NON-NLS-1$ fImportButton.setLayoutData(getButtonGridData(fImportButton)); fImportButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { import_(); } }); fExportButton= new Button(buttons, SWT.PUSH); fExportButton.setText(TemplateMessages.getString("TemplatePreferencePage.export")); //$NON-NLS-1$ fExportButton.setLayoutData(getButtonGridData(fExportButton)); fExportButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { export(); } }); fExportAllButton= new Button(buttons, SWT.PUSH); fExportAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.export.all")); //$NON-NLS-1$ fExportAllButton.setLayoutData(getButtonGridData(fExportAllButton)); fExportAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { exportAll(); } }); fEnableAllButton= new Button(buttons, SWT.PUSH); fEnableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.enable.all")); //$NON-NLS-1$ fEnableAllButton.setLayoutData(getButtonGridData(fEnableAllButton)); fEnableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { enableAll(true); } }); fDisableAllButton= new Button(buttons, SWT.PUSH); fDisableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.disable.all")); //$NON-NLS-1$ fDisableAllButton.setLayoutData(getButtonGridData(fDisableAllButton)); fDisableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { enableAll(false); } }); fPatternViewer= createViewer(parent); fFormatButton= new Button(parent, SWT.CHECK); fFormatButton.setText(TemplateMessages.getString("TemplatePreferencePage.use.code.formatter")); //$NON-NLS-1$ GridData gd1= new GridData(); gd1.horizontalSpan= 2; fFormatButton.setLayoutData(gd1); fTableViewer.setInput(fTemplates); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fFormatButton.setSelection(prefs.getBoolean(PREF_FORMAT_TEMPLATES)); updateButtons(); configureTableResizing(innerParent, buttons, table, column1, column2, column3); WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.TEMPLATE_PREFERENCE_PAGE); return parent; } /** * Correctly resizes the table so no phantom columns appear */ private static void configureTableResizing(final Composite parent, final Composite buttons, final Table table, final TableColumn column1, final TableColumn column2, final TableColumn column3) { parent.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { Rectangle area= parent.getClientArea(); Point preferredSize= table.computeSize(SWT.DEFAULT, SWT.DEFAULT); int width= area.width - 2 * table.getBorderWidth(); if (preferredSize.y > area.height) { // Subtract the scrollbar width from the total column width // if a vertical scrollbar will be required Point vBarSize = table.getVerticalBar().getSize(); width -= vBarSize.x; } width -= buttons.getSize().x; Point oldSize= table.getSize(); if (oldSize.x > width) { // table is getting smaller so make the columns // smaller first and then resize the table to // match the client area width column1.setWidth(width/4); column2.setWidth(width/4); column3.setWidth(width - (column1.getWidth() + column2.getWidth())); table.setSize(width, area.height); } else { // table is getting bigger so make the table // bigger first and then make the columns wider // to match the client area width table.setSize(width, area.height); column1.setWidth(width / 4); column2.setWidth(width / 4); column3.setWidth(width - (column1.getWidth() + column2.getWidth())); } } }); } private Template[] getEnabledTemplates() { Template[] templates= fTemplates.getTemplates(); List list= new ArrayList(templates.length); for (int i= 0; i != templates.length; i++) if (templates[i].isEnabled()) list.add(templates[i]); return (Template[]) list.toArray(new Template[list.size()]); } private SourceViewer createViewer(Composite parent) { Label label= new Label(parent, SWT.NONE); label.setText(TemplateMessages.getString("TemplatePreferencePage.preview")); //$NON-NLS-1$ GridData data= new GridData(); data.horizontalSpan= 2; label.setLayoutData(data); SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); IDocument document= new Document(); IDocumentPartitioner partitioner= tools.createDocumentPartitioner(); document.setDocumentPartitioner(partitioner); partitioner.connect(document); viewer.configure(new JavaSourceViewerConfiguration(tools, null)); viewer.setEditable(false); viewer.setDocument(document); viewer.getTextWidget().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); Control control= viewer.getControl(); data= new GridData(GridData.FILL_BOTH); data.horizontalSpan= 2; data.heightHint= convertHeightInCharsToPixels(5); control.setLayoutData(data); return viewer; } private static GridData getButtonGridData(Button button) { GridData data= new GridData(GridData.FILL_HORIZONTAL); data.widthHint= SWTUtil.getButtonWidthHint(button); data.heightHint= SWTUtil.getButtonHeigthHint(button); return data; } private void selectionChanged1() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); if (selection.size() == 1) { Template template= (Template) selection.getFirstElement(); fPatternViewer.getDocument().set(template.getPattern()); } else { fPatternViewer.getDocument().set(""); //$NON-NLS-1$ } updateButtons(); } private void updateButtons() { int selectionCount= ((IStructuredSelection) fTableViewer.getSelection()).size(); int itemCount= fTableViewer.getTable().getItemCount(); fEditButton.setEnabled(selectionCount == 1); fExportButton.setEnabled(selectionCount > 0); fRemoveButton.setEnabled(selectionCount > 0 && selectionCount <= itemCount); fEnableAllButton.setEnabled(itemCount > 0); fDisableAllButton.setEnabled(itemCount > 0); } private void add() { Template template= new Template(); template.setContext(CONTEXTS[0]); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, false, true, CONTEXTS); if (dialog.open() == EditTemplateDialog.OK) { fTemplates.add(template); fTableViewer.refresh(); fTableViewer.setChecked(template, template.isEnabled()); fTableViewer.setSelection(new StructuredSelection(template)); } } private void edit() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Object[] objects= selection.toArray(); if ((objects == null) || (objects.length != 1)) return; Template template= (Template) selection.getFirstElement(); edit(template); } private void edit(Template template) { Template newTemplate= new Template(template); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, true, CONTEXTS); if (dialog.open() == EditTemplateDialog.OK) { if (!newTemplate.getName().equals(template.getName()) && MessageDialog.openQuestion(getShell(), TemplateMessages.getString("TemplatePreferencePage.question.create.new.title"), //$NON-NLS-1$ TemplateMessages.getString("TemplatePreferencePage.question.create.new.message"))) //$NON-NLS-1$ { template= newTemplate; fTemplates.add(template); fTableViewer.refresh(); } else { template.setName(newTemplate.getName()); template.setDescription(newTemplate.getDescription()); template.setContext(newTemplate.getContextTypeName()); template.setPattern(newTemplate.getPattern()); fTableViewer.refresh(template); } fTableViewer.setChecked(template, template.isEnabled()); fTableViewer.setSelection(new StructuredSelection(template)); } } private void import_() { FileDialog dialog= new FileDialog(getShell()); dialog.setText(TemplateMessages.getString("TemplatePreferencePage.import.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.import.extension")}); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; try { fTemplates.addFromFile(new File(path), true); fTableViewer.refresh(); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); } catch (CoreException e) { openReadErrorDialog(e); } } private void exportAll() { export(fTemplates); } private void export() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Object[] templates= selection.toArray(); TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag()); for (int i= 0; i != templates.length; i++) templateSet.add((Template) templates[i]); export(templateSet); } private void export(TemplateSet templateSet) { FileDialog dialog= new FileDialog(getShell(), SWT.SAVE); dialog.setText(TemplateMessages.getFormattedString("TemplatePreferencePage.export.title", new Integer(templateSet.getTemplates().length))); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.export.extension")}); //$NON-NLS-1$ dialog.setFileName(TemplateMessages.getString("TemplatePreferencePage.export.filename")); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; File file= new File(path); if (!file.exists() || confirmOverwrite(file)) { try { templateSet.saveToFile(file); } catch (CoreException e) { JavaPlugin.log(e); openWriteErrorDialog(e); } } } private boolean confirmOverwrite(File file) { return MessageDialog.openQuestion(getShell(), TemplateMessages.getString("TemplatePreferencePage.export.exists.title"), //$NON-NLS-1$ TemplateMessages.getFormattedString("TemplatePreferencePage.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ } private void remove() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Iterator elements= selection.iterator(); while (elements.hasNext()) { Template template= (Template) elements.next(); fTemplates.remove(template); } fTableViewer.refresh(); } private void enableAll(boolean enable) { Template[] templates= fTemplates.getTemplates(); for (int i= 0; i != templates.length; i++) templates[i].setEnabled(enable); fTableViewer.setAllChecked(enable); } /* * @see IWorkbenchPreferencePage#init(IWorkbench) */ public void init(IWorkbench workbench) {} /* * @see Control#setVisible(boolean) */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) setTitle(TemplateMessages.getString("TemplatePreferencePage.title")); //$NON-NLS-1$ } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fFormatButton.setSelection(prefs.getDefaultBoolean(PREF_FORMAT_TEMPLATES)); try { fTemplates.restoreDefaults(); } catch (CoreException e) { JavaPlugin.log(e); openReadErrorDialog(e); } // refresh fTableViewer.refresh(); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); } /* * @see PreferencePage#performOk() */ public boolean performOk() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); prefs.setValue(PREF_FORMAT_TEMPLATES, fFormatButton.getSelection()); try { fTemplates.save(); } catch (CoreException e) { JavaPlugin.log(e); openWriteErrorDialog(e); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /* * @see PreferencePage#performCancel() */ public boolean performCancel() { try { fTemplates.reset(); } catch (CoreException e) { JavaPlugin.log(e); openReadErrorDialog(e); } return super.performCancel(); } private void openReadErrorDialog(CoreException e) { ErrorDialog.openError(getShell(), TemplateMessages.getString("TemplatePreferencePage.error.read.title"), //$NON-NLS-1$ null, e.getStatus()); } private void openWriteErrorDialog(CoreException e) { ErrorDialog.openError(getShell(), TemplateMessages.getString("TemplatePreferencePage.error.write.title"), //$NON-NLS-1$ null, e.getStatus()); } }
31,236
Bug 31236 SAXParseException should be supressed, i think
20030206 you get this exception if you try to import templates from an empty file not sure if this should be supressed somehow !ENTRY org.eclipse.jdt.ui 4 10002 Feb 07, 2003 11:55:45.646 !MESSAGE Error occurred while reading templates. !STACK 0 org.xml.sax.SAXParseException: Premature end of file. at org.apache.xerces.parsers.DOMParser.parse(DOMParser.java:235) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse (DocumentBuilderImpl.java:209) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromStream (TemplateSet.java:95) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromFile (TemplateSet.java:70) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.import_ (CodeTemplateBlock.java:363) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.doButtonPressed (CodeTemplateBlock.java:340) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock$CodeTemplateAdapter.cu stomButtonPressed(CodeTemplateBlock.java:67) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPress ed(TreeListDialogField.java:165) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSel ected(TreeListDialogField.java:380) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.access$2 (TreeListDialogField.java:376) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSel ected(TreeListDialogField.java:343) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
087f233
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T16:26:05Z
2003-02-07T12:13:20Z
org.eclipse.jdt.ui/core
31,236
Bug 31236 SAXParseException should be supressed, i think
20030206 you get this exception if you try to import templates from an empty file not sure if this should be supressed somehow !ENTRY org.eclipse.jdt.ui 4 10002 Feb 07, 2003 11:55:45.646 !MESSAGE Error occurred while reading templates. !STACK 0 org.xml.sax.SAXParseException: Premature end of file. at org.apache.xerces.parsers.DOMParser.parse(DOMParser.java:235) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse (DocumentBuilderImpl.java:209) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromStream (TemplateSet.java:95) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromFile (TemplateSet.java:70) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.import_ (CodeTemplateBlock.java:363) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.doButtonPressed (CodeTemplateBlock.java:340) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock$CodeTemplateAdapter.cu stomButtonPressed(CodeTemplateBlock.java:67) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPress ed(TreeListDialogField.java:165) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSel ected(TreeListDialogField.java:380) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.access$2 (TreeListDialogField.java:376) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSel ected(TreeListDialogField.java:343) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
087f233
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T16:26:05Z
2003-02-07T12:13:20Z
extension/org/eclipse/jdt/internal/corext/template/TemplateSet.java
31,236
Bug 31236 SAXParseException should be supressed, i think
20030206 you get this exception if you try to import templates from an empty file not sure if this should be supressed somehow !ENTRY org.eclipse.jdt.ui 4 10002 Feb 07, 2003 11:55:45.646 !MESSAGE Error occurred while reading templates. !STACK 0 org.xml.sax.SAXParseException: Premature end of file. at org.apache.xerces.parsers.DOMParser.parse(DOMParser.java:235) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse (DocumentBuilderImpl.java:209) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromStream (TemplateSet.java:95) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromFile (TemplateSet.java:70) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.import_ (CodeTemplateBlock.java:363) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.doButtonPressed (CodeTemplateBlock.java:340) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock$CodeTemplateAdapter.cu stomButtonPressed(CodeTemplateBlock.java:67) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPress ed(TreeListDialogField.java:165) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSel ected(TreeListDialogField.java:380) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.access$2 (TreeListDialogField.java:376) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSel ected(TreeListDialogField.java:343) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
087f233
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T16:26:05Z
2003-02-07T12:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/IJavaStatusConstants.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui; /** * Defines status codes relevant to the Java UI plug-in. When a * Core exception is thrown, it contain a status object describing * the cause of the exception. The status objects originating from the * Java UI plug-in use the codes defined in this interface. */ public interface IJavaStatusConstants { // Java UI status constants start at 10000 to make sure that we don't // collide with resource and java model constants. public static final int INTERNAL_ERROR= 10001; /** * Status constant indicating that an exception occured on * storing or loading templates. */ public static final int TEMPLATE_IO_EXCEPTION = 10002; /** * Status constant indicating that an validateEdit call has changed the * content of a file on disk. */ public static final int VALIDATE_EDIT_CHANGED_CONTENT= 10003; /** * Status constant indicating that a <tt>ChangeAbortException</tt> has been * caught. */ public static final int CHANGE_ABORTED= 10004; }
31,236
Bug 31236 SAXParseException should be supressed, i think
20030206 you get this exception if you try to import templates from an empty file not sure if this should be supressed somehow !ENTRY org.eclipse.jdt.ui 4 10002 Feb 07, 2003 11:55:45.646 !MESSAGE Error occurred while reading templates. !STACK 0 org.xml.sax.SAXParseException: Premature end of file. at org.apache.xerces.parsers.DOMParser.parse(DOMParser.java:235) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse (DocumentBuilderImpl.java:209) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromStream (TemplateSet.java:95) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromFile (TemplateSet.java:70) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.import_ (CodeTemplateBlock.java:363) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.doButtonPressed (CodeTemplateBlock.java:340) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock$CodeTemplateAdapter.cu stomButtonPressed(CodeTemplateBlock.java:67) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPress ed(TreeListDialogField.java:165) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSel ected(TreeListDialogField.java:380) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.access$2 (TreeListDialogField.java:376) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSel ected(TreeListDialogField.java:343) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
087f233
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T16:26:05Z
2003-02-07T12:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeTemplateBlock.java
package org.eclipse.jdt.internal.ui.preferences; import java.io.File; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.template.CodeTemplates; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateSet; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField; /** */ public class CodeTemplateBlock { private class CodeTemplateAdapter implements ITreeListAdapter, IDialogFieldListener { private final Object[] NO_CHILDREN= new Object[0]; private CodeTemplates fTemplates; public CodeTemplateAdapter(CodeTemplates templates) { fTemplates= templates; } public void customButtonPressed(TreeListDialogField field, int index) { doButtonPressed(index, field.getSelectedElements()); } public void selectionChanged(TreeListDialogField field) { List selected= field.getSelectedElements(); field.enableButton(IDX_EDIT, canEdit(selected)); field.enableButton(IDX_EXPORT, !selected.isEmpty()); updateSourceViewerInput(selected); } public void doubleClicked(TreeListDialogField field) { List selected= field.getSelectedElements(); if (canEdit(selected)) { doButtonPressed(IDX_EDIT, selected); } } public Object[] getChildren(TreeListDialogField field, Object element) { if (element == COMMENT_NODE || element == CODE_NODE) { return getTemplateOfCategory(element == COMMENT_NODE); } return NO_CHILDREN; } public Object getParent(TreeListDialogField field, Object element) { if (element instanceof Template) { Template template= (Template) element; if (template.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) { return COMMENT_NODE; } return CODE_NODE; } return null; } public boolean hasChildren(TreeListDialogField field, Object element) { return (element == COMMENT_NODE || element == CODE_NODE); } public void dialogFieldChanged(DialogField field) { } public void keyPressed(TreeListDialogField field, KeyEvent event) { } } private static class CodeTemplateLabelProvider extends LabelProvider { /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { if (element == COMMENT_NODE) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG); } if (element == CODE_NODE) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPCONT); } Template template = (Template) element; String name= template.getName(); if (CodeTemplates.CATCHBLOCK.equals(name)) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); } else if (CodeTemplates.METHODSTUB.equals(name)) { return JavaPluginImages.get(JavaPluginImages.IMG_MISC_DEFAULT); } else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) { ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry(); return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE)); } else if (CodeTemplates.NEWTYPE.equals(name)) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CUNIT); } else if (CodeTemplates.TYPECOMMENT.equals(name)) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS); } else if (CodeTemplates.METHODCOMMENT.equals(name)) { return JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED); } else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) { ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry(); return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PROTECTED, JavaElementImageDescriptor.OVERRIDES, JavaElementImageProvider.SMALL_SIZE)); } else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) { ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry(); return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE)); } return null; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { if (element == COMMENT_NODE || element == CODE_NODE) { return (String) element; } Template template = (Template) element; String name= template.getName(); if (CodeTemplates.CATCHBLOCK.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$ } else if (CodeTemplates.METHODSTUB.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$ } else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$ } else if (CodeTemplates.NEWTYPE.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$ } else if (CodeTemplates.TYPECOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.METHODCOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$ } return template.getDescription(); } } private final static int IDX_EDIT= 0; private final static int IDX_IMPORT= 2; private final static int IDX_EXPORT= 3; private final static int IDX_EXPORTALL= 4; protected final static Object COMMENT_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$ protected final static Object CODE_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$ private static final String PREF_JAVADOC_STUBS= PreferenceConstants.CODEGEN_ADD_COMMENTS; private TreeListDialogField fCodeTemplateTree; private SelectionButtonDialogField fCreateJavaDocComments; protected CodeTemplates fTemplates; private PixelConverter fPixelConverter; private SourceViewer fPatternViewer; private Control fSWTWidget; public CodeTemplateBlock() { fTemplates= CodeTemplates.getInstance(); CodeTemplateAdapter adapter= new CodeTemplateAdapter(fTemplates); String[] buttonLabels= new String[] { /* IDX_EDIT*/ PreferencesMessages.getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$ /* */ null, /* IDX_IMPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$ /* IDX_EXPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$ /* IDX_EXPORTALL */ PreferencesMessages.getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$ }; fCodeTemplateTree= new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider()); fCodeTemplateTree.setDialogFieldListener(adapter); fCodeTemplateTree.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$ fCodeTemplateTree.enableButton(IDX_EXPORT, false); fCodeTemplateTree.enableButton(IDX_EDIT, false); fCodeTemplateTree.addElement(COMMENT_NODE); fCodeTemplateTree.addElement(CODE_NODE); fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK); fCreateJavaDocComments.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$ fCreateJavaDocComments.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS)); fCodeTemplateTree.selectFirstElement(); } protected Control createContents(Composite parent) { fPixelConverter= new PixelConverter(parent); fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); //layout.marginHeight= 0; //layout.marginWidth= 0; layout.numColumns= 2; composite.setLayout(layout); fCreateJavaDocComments.doFillIntoGrid(composite, 2); fCodeTemplateTree.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2); LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null)); fPatternViewer= createViewer(composite, 2); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private SourceViewer createViewer(Composite parent, int nColumns) { Label label= new Label(parent, SWT.NONE); label.setText(PreferencesMessages.getString("CodeTemplateBlock.preview")); //$NON-NLS-1$ GridData data= new GridData(); data.horizontalSpan= nColumns; label.setLayoutData(data); SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); IDocument document= new Document(); IDocumentPartitioner partitioner= tools.createDocumentPartitioner(); document.setDocumentPartitioner(partitioner); partitioner.connect(document); viewer.configure(new JavaSourceViewerConfiguration(tools, null)); viewer.setEditable(false); viewer.setDocument(document); viewer.getTextWidget().setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); Control control= viewer.getControl(); data= new GridData(GridData.FILL_BOTH); data.horizontalSpan= nColumns; data.heightHint= fPixelConverter.convertHeightInCharsToPixels(5); control.setLayoutData(data); return viewer; } protected Template[] getTemplateOfCategory(boolean isComment) { ArrayList res= new ArrayList(); Template[] templates= fTemplates.getTemplates(); for (int i= 0; i < templates.length; i++) { Template curr= templates[i]; if (isComment == curr.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) { res.add(curr); } } return (Template[]) res.toArray(new Template[res.size()]); } protected static boolean canEdit(List selected) { return selected.size() == 1 && (selected.get(0) instanceof Template); } protected void updateSourceViewerInput(List selection) { if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) { return; } if (selection.size() == 1 && selection.get(0) instanceof Template) { Template template= (Template) selection.get(0); fPatternViewer.getDocument().set(template.getPattern()); } else { fPatternViewer.getDocument().set(""); //$NON-NLS-1$ } } protected void doButtonPressed(int buttonIndex, List selected) { if (buttonIndex == IDX_EDIT) { edit((Template) selected.get(0)); } else if (buttonIndex == IDX_EXPORT) { export(selected); } else if (buttonIndex == IDX_EXPORTALL) { exportAll(); } else if (buttonIndex == IDX_IMPORT) { import_(); } } private void edit(Template template) { Template newTemplate= new Template(template); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, false, new String[0]); if (dialog.open() == EditTemplateDialog.OK) { // changed template.setDescription(newTemplate.getDescription()); template.setPattern(newTemplate.getPattern()); fCodeTemplateTree.refresh(template); fCodeTemplateTree.selectElements(new StructuredSelection(template)); } } private void import_() { FileDialog dialog= new FileDialog(getShell()); dialog.setText(PreferencesMessages.getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.import.extension")}); //$NON-NLS-1$ String path= dialog.open(); if (path != null) { try { fTemplates.addFromFile(new File(path), false); } catch (CoreException e) { openReadErrorDialog(e); } fCodeTemplateTree.refresh(); } } private void exportAll() { export(fTemplates); } private void export(List selected) { TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag()); for (int i= 0; i < selected.size(); i++) { Object curr= selected.get(i); if (curr instanceof Template) { addToTemplateSet(templateSet, (Template) curr); } else { Template[] templates= getTemplateOfCategory(curr == COMMENT_NODE); for (int k= 0; k < templates.length; k++) { addToTemplateSet(templateSet, templates[k]); } } } export(templateSet); } private void addToTemplateSet(TemplateSet set, Template template) { if (set.getFirstTemplate(template.getName()) == null) { set.add(template); } } private void export(TemplateSet templateSet) { FileDialog dialog= new FileDialog(getShell(), SWT.SAVE); dialog.setText(PreferencesMessages.getFormattedString("CodeTemplateBlock.export.title", String.valueOf(templateSet.getTemplates().length))); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.export.extension")}); //$NON-NLS-1$ dialog.setFileName(PreferencesMessages.getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; File file= new File(path); if (!file.exists() || confirmOverwrite(file)) { try { templateSet.saveToFile(file); } catch (CoreException e) { JavaPlugin.log(e); openWriteErrorDialog(e); } } } private boolean confirmOverwrite(File file) { return MessageDialog.openQuestion(getShell(), PreferencesMessages.getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$ PreferencesMessages.getFormattedString("CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ } public void performDefaults() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS)); try { fTemplates.restoreDefaults(); } catch (CoreException e) { JavaPlugin.log(e); openReadErrorDialog(e); } // refresh fCodeTemplateTree.refresh(); } public boolean performOk(boolean enabled) { IPreferenceStore prefs= PreferenceConstants.getPreferenceStore(); prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected()); JavaPlugin.getDefault().savePluginPreferences(); try { fTemplates.save(); } catch (CoreException e) { JavaPlugin.log(e); openWriteErrorDialog(e); } return true; } public void performCancel() { try { fTemplates.reset(); } catch (CoreException e) { openReadErrorDialog(e); } } private void openReadErrorDialog(CoreException e) { String title= PreferencesMessages.getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } private void openWriteErrorDialog(CoreException e) { String title= PreferencesMessages.getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } }
31,236
Bug 31236 SAXParseException should be supressed, i think
20030206 you get this exception if you try to import templates from an empty file not sure if this should be supressed somehow !ENTRY org.eclipse.jdt.ui 4 10002 Feb 07, 2003 11:55:45.646 !MESSAGE Error occurred while reading templates. !STACK 0 org.xml.sax.SAXParseException: Premature end of file. at org.apache.xerces.parsers.DOMParser.parse(DOMParser.java:235) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse (DocumentBuilderImpl.java:209) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromStream (TemplateSet.java:95) at org.eclipse.jdt.internal.corext.template.TemplateSet.addFromFile (TemplateSet.java:70) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.import_ (CodeTemplateBlock.java:363) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock.doButtonPressed (CodeTemplateBlock.java:340) at org.eclipse.jdt.internal.ui.preferences.CodeTemplateBlock$CodeTemplateAdapter.cu stomButtonPressed(CodeTemplateBlock.java:67) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPress ed(TreeListDialogField.java:165) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSel ected(TreeListDialogField.java:380) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.access$2 (TreeListDialogField.java:376) at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSel ected(TreeListDialogField.java:343) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
087f233
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T16:26:05Z
2003-02-07T12:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TemplatePreferencePage.java
package org.eclipse.jdt.internal.ui.preferences; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplateSet; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContextType; import org.eclipse.jdt.internal.corext.template.java.JavaDocContextType; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.template.TemplateContentProvider; import org.eclipse.jdt.internal.ui.util.SWTUtil; public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { Template template = (Template) element; switch (columnIndex) { case 0: return template.getName(); case 1: return template.getContextTypeName(); case 2: return template.getDescription(); default: return ""; //$NON-NLS-1$ } } } // preference store keys private static final String PREF_FORMAT_TEMPLATES= PreferenceConstants.TEMPLATES_USE_CODEFORMATTER; private final String[] CONTEXTS= new String[] { JavaContextType.NAME, JavaDocContextType.NAME }; private Templates fTemplates; private CheckboxTableViewer fTableViewer; private Button fAddButton; private Button fEditButton; private Button fImportButton; private Button fExportButton; private Button fExportAllButton; private Button fRemoveButton; private Button fEnableAllButton; private Button fDisableAllButton; private SourceViewer fPatternViewer; private Button fFormatButton; public TemplatePreferencePage() { super(); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(TemplateMessages.getString("TemplatePreferencePage.message")); //$NON-NLS-1$ fTemplates= Templates.getInstance(); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite ancestor) { Composite parent= new Composite(ancestor, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; parent.setLayout(layout); Composite innerParent= new Composite(parent, SWT.NONE); GridLayout innerLayout= new GridLayout(); innerLayout.numColumns= 2; innerLayout.marginHeight= 0; innerLayout.marginWidth= 0; innerParent.setLayout(innerLayout); GridData gd= new GridData(GridData.FILL_BOTH); gd.horizontalSpan= 2; innerParent.setLayoutData(gd); Table table= new Table(innerParent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(3); data.heightHint= convertHeightInCharsToPixels(10); table.setLayoutData(data); table.setHeaderVisible(true); table.setLinesVisible(true); TableLayout tableLayout= new TableLayout(); table.setLayout(tableLayout); TableColumn column1= new TableColumn(table, SWT.NONE); column1.setText(TemplateMessages.getString("TemplatePreferencePage.column.name")); //$NON-NLS-1$ TableColumn column2= new TableColumn(table, SWT.NONE); column2.setText(TemplateMessages.getString("TemplatePreferencePage.column.context")); //$NON-NLS-1$ TableColumn column3= new TableColumn(table, SWT.NONE); column3.setText(TemplateMessages.getString("TemplatePreferencePage.column.description")); //$NON-NLS-1$ fTableViewer= new CheckboxTableViewer(table); fTableViewer.setLabelProvider(new TemplateLabelProvider()); fTableViewer.setContentProvider(new TemplateContentProvider()); fTableViewer.setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object object1, Object object2) { if ((object1 instanceof Template) && (object2 instanceof Template)) { Template left= (Template) object1; Template right= (Template) object2; int result= left.getName().compareToIgnoreCase(right.getName()); if (result != 0) return result; return left.getDescription().compareToIgnoreCase(right.getDescription()); } return super.compare(viewer, object1, object2); } public boolean isSorterProperty(Object element, String property) { return true; } }); fTableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent e) { edit(); } }); fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent e) { selectionChanged1(); } }); fTableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { Template template= (Template) event.getElement(); template.setEnabled(event.getChecked()); } }); Composite buttons= new Composite(innerParent, SWT.NONE); buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; buttons.setLayout(layout); fAddButton= new Button(buttons, SWT.PUSH); fAddButton.setText(TemplateMessages.getString("TemplatePreferencePage.new")); //$NON-NLS-1$ fAddButton.setLayoutData(getButtonGridData(fAddButton)); fAddButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { add(); } }); fEditButton= new Button(buttons, SWT.PUSH); fEditButton.setText(TemplateMessages.getString("TemplatePreferencePage.edit")); //$NON-NLS-1$ fEditButton.setLayoutData(getButtonGridData(fEditButton)); fEditButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { edit(); } }); fRemoveButton= new Button(buttons, SWT.PUSH); fRemoveButton.setText(TemplateMessages.getString("TemplatePreferencePage.remove")); //$NON-NLS-1$ fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton)); fRemoveButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { remove(); } }); fImportButton= new Button(buttons, SWT.PUSH); fImportButton.setText(TemplateMessages.getString("TemplatePreferencePage.import")); //$NON-NLS-1$ fImportButton.setLayoutData(getButtonGridData(fImportButton)); fImportButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { import_(); } }); fExportButton= new Button(buttons, SWT.PUSH); fExportButton.setText(TemplateMessages.getString("TemplatePreferencePage.export")); //$NON-NLS-1$ fExportButton.setLayoutData(getButtonGridData(fExportButton)); fExportButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { export(); } }); fExportAllButton= new Button(buttons, SWT.PUSH); fExportAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.export.all")); //$NON-NLS-1$ fExportAllButton.setLayoutData(getButtonGridData(fExportAllButton)); fExportAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { exportAll(); } }); fEnableAllButton= new Button(buttons, SWT.PUSH); fEnableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.enable.all")); //$NON-NLS-1$ fEnableAllButton.setLayoutData(getButtonGridData(fEnableAllButton)); fEnableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { enableAll(true); } }); fDisableAllButton= new Button(buttons, SWT.PUSH); fDisableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.disable.all")); //$NON-NLS-1$ fDisableAllButton.setLayoutData(getButtonGridData(fDisableAllButton)); fDisableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { enableAll(false); } }); fPatternViewer= createViewer(parent); fFormatButton= new Button(parent, SWT.CHECK); fFormatButton.setText(TemplateMessages.getString("TemplatePreferencePage.use.code.formatter")); //$NON-NLS-1$ GridData gd1= new GridData(); gd1.horizontalSpan= 2; fFormatButton.setLayoutData(gd1); fTableViewer.setInput(fTemplates); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fFormatButton.setSelection(prefs.getBoolean(PREF_FORMAT_TEMPLATES)); updateButtons(); configureTableResizing(innerParent, buttons, table, column1, column2, column3); WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.TEMPLATE_PREFERENCE_PAGE); return parent; } /** * Correctly resizes the table so no phantom columns appear */ private static void configureTableResizing(final Composite parent, final Composite buttons, final Table table, final TableColumn column1, final TableColumn column2, final TableColumn column3) { parent.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { Rectangle area= parent.getClientArea(); Point preferredSize= table.computeSize(SWT.DEFAULT, SWT.DEFAULT); int width= area.width - 2 * table.getBorderWidth(); if (preferredSize.y > area.height) { // Subtract the scrollbar width from the total column width // if a vertical scrollbar will be required Point vBarSize = table.getVerticalBar().getSize(); width -= vBarSize.x; } width -= buttons.getSize().x; Point oldSize= table.getSize(); if (oldSize.x > width) { // table is getting smaller so make the columns // smaller first and then resize the table to // match the client area width column1.setWidth(width/4); column2.setWidth(width/4); column3.setWidth(width - (column1.getWidth() + column2.getWidth())); table.setSize(width, area.height); } else { // table is getting bigger so make the table // bigger first and then make the columns wider // to match the client area width table.setSize(width, area.height); column1.setWidth(width / 4); column2.setWidth(width / 4); column3.setWidth(width - (column1.getWidth() + column2.getWidth())); } } }); } private Template[] getEnabledTemplates() { Template[] templates= fTemplates.getTemplates(); List list= new ArrayList(templates.length); for (int i= 0; i != templates.length; i++) if (templates[i].isEnabled()) list.add(templates[i]); return (Template[]) list.toArray(new Template[list.size()]); } private SourceViewer createViewer(Composite parent) { Label label= new Label(parent, SWT.NONE); label.setText(TemplateMessages.getString("TemplatePreferencePage.preview")); //$NON-NLS-1$ GridData data= new GridData(); data.horizontalSpan= 2; label.setLayoutData(data); SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); IDocument document= new Document(); IDocumentPartitioner partitioner= tools.createDocumentPartitioner(); document.setDocumentPartitioner(partitioner); partitioner.connect(document); viewer.configure(new JavaSourceViewerConfiguration(tools, null)); viewer.setEditable(false); viewer.setDocument(document); viewer.getTextWidget().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); Control control= viewer.getControl(); data= new GridData(GridData.FILL_BOTH); data.horizontalSpan= 2; data.heightHint= convertHeightInCharsToPixels(5); control.setLayoutData(data); return viewer; } private static GridData getButtonGridData(Button button) { GridData data= new GridData(GridData.FILL_HORIZONTAL); data.widthHint= SWTUtil.getButtonWidthHint(button); data.heightHint= SWTUtil.getButtonHeigthHint(button); return data; } private void selectionChanged1() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); if (selection.size() == 1) { Template template= (Template) selection.getFirstElement(); fPatternViewer.getDocument().set(template.getPattern()); } else { fPatternViewer.getDocument().set(""); //$NON-NLS-1$ } updateButtons(); } private void updateButtons() { int selectionCount= ((IStructuredSelection) fTableViewer.getSelection()).size(); int itemCount= fTableViewer.getTable().getItemCount(); fEditButton.setEnabled(selectionCount == 1); fExportButton.setEnabled(selectionCount > 0); fRemoveButton.setEnabled(selectionCount > 0 && selectionCount <= itemCount); fEnableAllButton.setEnabled(itemCount > 0); fDisableAllButton.setEnabled(itemCount > 0); } private void add() { Template template= new Template(); template.setContext(CONTEXTS[0]); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, false, true, CONTEXTS); if (dialog.open() == EditTemplateDialog.OK) { fTemplates.add(template); fTableViewer.refresh(); fTableViewer.setChecked(template, template.isEnabled()); fTableViewer.setSelection(new StructuredSelection(template)); } } private void edit() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Object[] objects= selection.toArray(); if ((objects == null) || (objects.length != 1)) return; Template template= (Template) selection.getFirstElement(); edit(template); } private void edit(Template template) { Template newTemplate= new Template(template); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, true, CONTEXTS); if (dialog.open() == EditTemplateDialog.OK) { if (!newTemplate.getName().equals(template.getName()) && MessageDialog.openQuestion(getShell(), TemplateMessages.getString("TemplatePreferencePage.question.create.new.title"), //$NON-NLS-1$ TemplateMessages.getString("TemplatePreferencePage.question.create.new.message"))) //$NON-NLS-1$ { template= newTemplate; fTemplates.add(template); fTableViewer.refresh(); } else { template.setName(newTemplate.getName()); template.setDescription(newTemplate.getDescription()); template.setContext(newTemplate.getContextTypeName()); template.setPattern(newTemplate.getPattern()); fTableViewer.refresh(template); } fTableViewer.setChecked(template, template.isEnabled()); fTableViewer.setSelection(new StructuredSelection(template)); } } private void import_() { FileDialog dialog= new FileDialog(getShell()); dialog.setText(TemplateMessages.getString("TemplatePreferencePage.import.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.import.extension")}); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; try { fTemplates.addFromFile(new File(path), true); fTableViewer.refresh(); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); } catch (CoreException e) { openReadErrorDialog(e); } } private void exportAll() { export(fTemplates); } private void export() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Object[] templates= selection.toArray(); TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag()); for (int i= 0; i != templates.length; i++) templateSet.add((Template) templates[i]); export(templateSet); } private void export(TemplateSet templateSet) { FileDialog dialog= new FileDialog(getShell(), SWT.SAVE); dialog.setText(TemplateMessages.getFormattedString("TemplatePreferencePage.export.title", new Integer(templateSet.getTemplates().length))); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.export.extension")}); //$NON-NLS-1$ dialog.setFileName(TemplateMessages.getString("TemplatePreferencePage.export.filename")); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; File file= new File(path); if (file.isHidden()) { String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$ String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } if (file.exists() && !file.canWrite()) { String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$ String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } if (!file.exists() || confirmOverwrite(file)) { try { templateSet.saveToFile(file); } catch (CoreException e) { if (e.getStatus().getException() instanceof FileNotFoundException) { String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$ String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.fileNotFound", e.getStatus().getException().getLocalizedMessage()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } JavaPlugin.log(e); openWriteErrorDialog(e); } } } private boolean confirmOverwrite(File file) { return MessageDialog.openQuestion(getShell(), TemplateMessages.getString("TemplatePreferencePage.export.exists.title"), //$NON-NLS-1$ TemplateMessages.getFormattedString("TemplatePreferencePage.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ } private void remove() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Iterator elements= selection.iterator(); while (elements.hasNext()) { Template template= (Template) elements.next(); fTemplates.remove(template); } fTableViewer.refresh(); } private void enableAll(boolean enable) { Template[] templates= fTemplates.getTemplates(); for (int i= 0; i != templates.length; i++) templates[i].setEnabled(enable); fTableViewer.setAllChecked(enable); } /* * @see IWorkbenchPreferencePage#init(IWorkbench) */ public void init(IWorkbench workbench) {} /* * @see Control#setVisible(boolean) */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) setTitle(TemplateMessages.getString("TemplatePreferencePage.title")); //$NON-NLS-1$ } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fFormatButton.setSelection(prefs.getDefaultBoolean(PREF_FORMAT_TEMPLATES)); try { fTemplates.restoreDefaults(); } catch (CoreException e) { JavaPlugin.log(e); openReadErrorDialog(e); } // refresh fTableViewer.refresh(); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); } /* * @see PreferencePage#performOk() */ public boolean performOk() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); prefs.setValue(PREF_FORMAT_TEMPLATES, fFormatButton.getSelection()); try { fTemplates.save(); } catch (CoreException e) { JavaPlugin.log(e); openWriteErrorDialog(e); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /* * @see PreferencePage#performCancel() */ public boolean performCancel() { try { fTemplates.reset(); } catch (CoreException e) { JavaPlugin.log(e); openReadErrorDialog(e); } return super.performCancel(); } private void openReadErrorDialog(CoreException e) { ErrorDialog.openError(getShell(), TemplateMessages.getString("TemplatePreferencePage.error.read.title"), //$NON-NLS-1$ null, e.getStatus()); } private void openWriteErrorDialog(CoreException e) { ErrorDialog.openError(getShell(), TemplateMessages.getString("TemplatePreferencePage.error.write.title"), //$NON-NLS-1$ null, e.getStatus()); } }
24,678
Bug 24678 New Variable Classpath Entry impossible to save
If you rc on your project and select properties and then java build path, select the library tab and then click add variable and then new. Now try enter a valid name and valid path and click ok. You now see this variable in the list but you can not click ok again. The only option is cancel which then doesn't save your new variable. The other pathway to this functionality works. You go to window preferences, properties, java, classpath variables and enter the variable. This way the variable does get saved.
resolved fixed
52952ec
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T17:16:49Z
2002-10-10T22:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ClasspathVariablesPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock; public class ClasspathVariablesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private VariableBlock fVariableBlock; /** * Constructor for ClasspathVariablesPreferencePage */ public ClasspathVariablesPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); fVariableBlock= new VariableBlock(true, null); setDescription(PreferencesMessages.getString("ClasspathVariablesPreferencePage.description")); //$NON-NLS-1$ } /** * @see PreferencePage#createContents(org.eclipse.swt.widgets.Composite) */ protected Control createContents(Composite parent) { WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.CP_VARIABLES_PREFERENCE_PAGE); return fVariableBlock.createContents(parent); } /** * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } /** * @see PreferencePage#performDefaults() */ protected void performDefaults() { fVariableBlock.performDefaults(); super.performDefaults(); } /** * @see PreferencePage#performOk() */ public boolean performOk() { JavaPlugin.getDefault().savePluginPreferences(); return fVariableBlock.performOk(); } private void updateStatus(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } }
24,678
Bug 24678 New Variable Classpath Entry impossible to save
If you rc on your project and select properties and then java build path, select the library tab and then click add variable and then new. Now try enter a valid name and valid path and click ok. You now see this variable in the list but you can not click ok again. The only option is cancel which then doesn't save your new variable. The other pathway to this functionality works. You go to window preferences, properties, java, classpath variables and enter the variable. This way the variable does get saved.
resolved fixed
52952ec
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T17:16:49Z
2002-10-10T22:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/EditVariableEntryDialog.java
package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.io.File; import java.util.List; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; /** */ public class EditVariableEntryDialog extends StatusDialog { /** * The path to which the archive variable points. * Null if invalid path or not resolvable. Must not exist. */ private IPath fFileVariablePath; private IStatus fNameStatus; private List fExistingEntries; private VariablePathDialogField fFileNameField; private CLabel fFullPathResolvedLabel; private IPath fEditEntry; /** * Constructor for EditVariableEntryDialog. * @param parent */ public EditVariableEntryDialog(Shell parent, IPath editEntry, List existingEntries) { super(parent); fExistingEntries= existingEntries; fExistingEntries.remove(editEntry); fEditEntry= editEntry; SourceAttachmentAdapter adapter= new SourceAttachmentAdapter(); fFileNameField= new VariablePathDialogField(adapter); fFileNameField.setDialogFieldListener(adapter); fFileNameField.setLabelText(NewWizardMessages.getString("EditVariableEntryDialog.filename.varlabel")); //$NON-NLS-1$ fFileNameField.setButtonLabel(NewWizardMessages.getString("EditVariableEntryDialog.filename.external.varbutton")); //$NON-NLS-1$ fFileNameField.setVariableButtonLabel(NewWizardMessages.getString("EditVariableEntryDialog.filename.variable.button")); //$NON-NLS-1$ fFileNameField.setText(fEditEntry.toString()); } public IPath getPath() { return new Path(fFileNameField.getText()); } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); Composite composite= (Composite) super.createDialogArea(parent); GridLayout layout= (GridLayout) composite.getLayout(); layout.numColumns= 3; int widthHint= convertWidthInCharsToPixels(50); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 3; // archive name field fFileNameField.doFillIntoGrid(composite, 4); LayoutUtil.setHorizontalSpan(fFileNameField.getLabelControl(null), 3); LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint); LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null)); // label that shows the resolved path for variable jars //DialogField.createEmptySpace(composite, 1); fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT); fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); fFullPathResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(composite, 2); fFileNameField.postSetFocusOnDialogField(parent.getDisplay()); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK); return composite; } private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { attachmentChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { attachmentDialogFieldChanged(field); } } private void attachmentChangeControlPressed(DialogField field) { if (field == fFileNameField) { IPath jarFilePath= chooseExtJarFile(); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } } } // ---------- IDialogFieldListener -------- private void attachmentDialogFieldChanged(DialogField field) { if (field == fFileNameField) { fNameStatus= updateFileNameStatus(); } doStatusLineUpdate(); } private IPath chooseExtJarFile() { IPath currPath= new Path(fFileNameField.getText()); IPath resolvedPath= getResolvedPath(currPath); File initialSelection= resolvedPath != null ? resolvedPath.toFile() : null; String currVariable= currPath.segment(0); JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), false, false); dialog.setTitle(NewWizardMessages.getString("EditVariableEntryDialog.extvardialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("EditVariableEntryDialog.extvardialog.description")); //$NON-NLS-1$ dialog.setInput(fFileVariablePath.toFile()); dialog.setInitialSelection(initialSelection); if (dialog.open() == JARFileSelectionDialog.OK) { File result= (File) dialog.getResult()[0]; IPath returnPath= new Path(result.getPath()).makeAbsolute(); return modifyPath(returnPath, currVariable); } return null; } private IPath getResolvedPath(IPath path) { if (path != null) { String varName= path.segment(0); if (varName != null) { IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { return varPath.append(path.removeFirstSegments(1)); } } } return null; } /** * Takes a path and replaces the beginning with a variable name * (if the beginning matches with the variables value) */ private IPath modifyPath(IPath path, String varName) { if (varName == null || path == null) { return null; } if (path.isEmpty()) { return new Path(varName); } IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { if (varPath.isPrefixOf(path)) { path= path.removeFirstSegments(varPath.segmentCount()); } else { path= new Path(path.lastSegment()); } } else { path= new Path(path.lastSegment()); } return new Path(varName).append(path); } private IStatus updateFileNameStatus() { StatusInfo status= new StatusInfo(); fFileVariablePath= null; String fileName= fFileNameField.getText(); if (fileName.length() == 0) { // no source attachment return status; } else { if (!Path.EMPTY.isValidPath(fileName)) { status.setError(NewWizardMessages.getString("EditVariableEntryDialog.filename.error.notvalid")); //$NON-NLS-1$ return status; } IPath filePath= new Path(fileName); IPath resolvedPath; if (filePath.getDevice() != null) { status.setError(NewWizardMessages.getString("EditVariableEntryDialog.filename.error.deviceinpath")); //$NON-NLS-1$ return status; } String varName= filePath.segment(0); if (varName == null) { status.setError(NewWizardMessages.getString("EditVariableEntryDialog.filename.error.notvalid")); //$NON-NLS-1$ return status; } fFileVariablePath= JavaCore.getClasspathVariable(varName); if (fFileVariablePath == null) { status.setError(NewWizardMessages.getString("EditVariableEntryDialog.filename.error.varnotexists")); //$NON-NLS-1$ return status; } resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1)); if (resolvedPath.isEmpty()) { status.setWarning(NewWizardMessages.getString("EditVariableEntryDialog.filename.warning.varempty")); //$NON-NLS-1$ return status; } File file= resolvedPath.toFile(); if (!file.isFile()) { String message= NewWizardMessages.getFormattedString("EditVariableEntryDialog.filename.error.filenotexists", resolvedPath.toOSString()); //$NON-NLS-1$ status.setWarning(message); return status; } } return status; } private String getResolvedLabelString(String path, boolean osPath) { IPath resolvedPath= getResolvedPath(new Path(path)); if (resolvedPath != null) { if (osPath) { return resolvedPath.toOSString(); } else { return resolvedPath.toString(); } } return ""; //$NON-NLS-1$ } private boolean canBrowseFileName() { // to browse with a variable JAR, the variable name must point to a directory if (fFileVariablePath != null) { return fFileVariablePath.toFile().isDirectory(); } return false; } private void doStatusLineUpdate() { fFileNameField.enableButton(canBrowseFileName()); // set the resolved path for variable jars if (fFullPathResolvedLabel != null) { fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); } IStatus status= fNameStatus; if (!status.matches(IStatus.ERROR)) { IPath path= getPath(); if (fExistingEntries.contains(path)) { String message= NewWizardMessages.getString("EditVariableEntryDialog.filename.error.alreadyexists"); //$NON-NLS-1$ status= new StatusInfo(IStatus.ERROR, message); } } updateStatus(status); } }
24,678
Bug 24678 New Variable Classpath Entry impossible to save
If you rc on your project and select properties and then java build path, select the library tab and then click add variable and then new. Now try enter a valid name and valid path and click ok. You now see this variable in the list but you can not click ok again. The only option is cancel which then doesn't save your new variable. The other pathway to this functionality works. You go to window preferences, properties, java, classpath variables and enter the variable. This way the variable does get saved.
resolved fixed
52952ec
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T17:16:49Z
2002-10-10T22:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/NewVariableEntryDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.io.File; import java.util.List; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; public class NewVariableEntryDialog extends StatusDialog { private class VariableSelectionListener implements IDoubleClickListener, ISelectionChangedListener { public void doubleClick(DoubleClickEvent event) { doDoubleClick(); } public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(); } } private final int EXTEND_ID= IDialogConstants.CLIENT_ID; private VariableBlock fVariableBlock; private Button fExtensionButton; private Button fOkButton; private IPath[] fResultPaths; private String fTitle; private boolean fFirstInvocation= true; /** * @deprecated Use NewVariableEntryDialog(Shell) and setTitle instead */ public NewVariableEntryDialog(Shell parent, String title, Object exsting) { this(parent); setTitle(title); } public NewVariableEntryDialog(Shell parent) { super(parent); int shellStyle= getShellStyle(); setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE); fVariableBlock= new VariableBlock(false, null); fResultPaths= null; } /* (non-Javadoc) * @see Window#configureShell(Shell) */ protected void configureShell(Shell shell) { super.configureShell(shell); WorkbenchHelp.setHelp(shell, IJavaHelpContextIds.NEW_VARIABLE_ENTRY_DIALOG); } protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); VariableSelectionListener listener= new VariableSelectionListener(); Composite composite= (Composite) super.createDialogArea(parent); Control control= fVariableBlock.createContents(composite); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(80); data.heightHint= convertHeightInCharsToPixels(15); control.setLayoutData(data); fVariableBlock.addDoubleClickListener(listener); fVariableBlock.addSelectionChangedListener(listener); return composite; } /** * @see Dialog#createButtonsForButtonBar(Composite) */ protected void createButtonsForButtonBar(Composite parent) { fOkButton= createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); fExtensionButton= createButton(parent, EXTEND_ID, NewWizardMessages.getString("NewVariableEntryDialog.addextension.button"), false); //$NON-NLS-1$ createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } protected void okPressed() { fVariableBlock.performOk(); super.okPressed(); } public IPath[] getResult() { return fResultPaths; } /* * @see IDoubleClickListener#doubleClick(DoubleClickEvent) */ private void doDoubleClick() { if (fOkButton.isEnabled()) { okPressed(); } else if (fExtensionButton.isEnabled()) { buttonPressed(EXTEND_ID); } } private void doSelectionChanged() { boolean isValidSelection= true; StatusInfo status= new StatusInfo(); List selected= fVariableBlock.getSelectedElements(); int nSelected= selected.size(); if (nSelected > 0) { fResultPaths= new Path[nSelected]; for (int i= 0; i < nSelected; i++) { CPVariableElement curr= (CPVariableElement) selected.get(i); fResultPaths[i]= new Path(curr.getName()); if (!curr.getPath().toFile().isFile()) { isValidSelection= false; status.setInfo(NewWizardMessages.getString("NewVariableEntryDialog.info.isfolder")); //$NON-NLS-1$ } } } else { isValidSelection= false; status.setInfo(NewWizardMessages.getString("NewVariableEntryDialog.info.noselection")); //$NON-NLS-1$ } if (isValidSelection && nSelected > 1) { String str= NewWizardMessages.getFormattedString("NewVariableEntryDialog.info.selected", String.valueOf(nSelected)); //$NON-NLS-1$ status.setInfo(str); } fExtensionButton.setEnabled(nSelected == 1 && !isValidSelection); fOkButton.setEnabled(isValidSelection); updateStatus(status); } private IPath[] chooseExtensions(CPVariableElement elem) { File file= elem.getPath().toFile(); JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), true, false); dialog.setTitle(NewWizardMessages.getString("NewVariableEntryDialog.ExtensionDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getFormattedString("NewVariableEntryDialog.ExtensionDialog.description", elem.getName())); //$NON-NLS-1$ dialog.setInput(file); if (dialog.open() == JARFileSelectionDialog.OK) { Object[] selected= dialog.getResult(); IPath[] paths= new IPath[selected.length]; for (int i= 0; i < selected.length; i++) { IPath filePath= new Path(((File) selected[i]).getPath()); IPath resPath= new Path(elem.getName()); for (int k= elem.getPath().segmentCount(); k < filePath.segmentCount(); k++) { resPath= resPath.append(filePath.segment(k)); } paths[i]= resPath; } return paths; } return null; } /* * @see Dialog#buttonPressed(int) */ protected void buttonPressed(int buttonId) { if (buttonId == EXTEND_ID) { List selected= fVariableBlock.getSelectedElements(); if (selected.size() == 1) { IPath[] extendedPaths= chooseExtensions((CPVariableElement) selected.get(0)); if (extendedPaths != null) { fResultPaths= extendedPaths; super.buttonPressed(IDialogConstants.OK_ID); } } } else { super.buttonPressed(buttonId); } } }
31,283
Bug 31283 Push down refactoring: Preview not resizable
20030206 1. select a method and choose 'push down' 2. in the dialog press the 'preview...' button 3. the dialog coming up can contain som long problem descriptions, but the dialog is not resizable
resolved fixed
266dcaf
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T17:33:10Z
2003-02-07T15:00:00Z
org.eclipse.jdt.ui/ui
31,283
Bug 31283 Push down refactoring: Preview not resizable
20030206 1. select a method and choose 'push down' 2. in the dialog press the 'preview...' button 3. the dialog coming up can contain som long problem descriptions, but the dialog is not resizable
resolved fixed
266dcaf
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T17:33:10Z
2003-02-07T15:00:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringStatusDialog.java
30,941
Bug 30941 Preferences default initialization. Can not do a syncExec
20030204 The initialization of the preference default currently contains a final Display display= Display.getDefault(); display.syncExec(new Runnable() { public void run() { Color c= display.getSystemColor(SWT.COLOR_GRAY); rgbs[0]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND); rgbs[1]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); rgbs[2]= c.getRGB(); } }); We should avoid and remove this as this is a candidate for a deadlock.
resolved fixed
45418a9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T18:46:22Z
2003-02-05T10:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; 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.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.action.Action; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; /* * The page for setting the editor options. */ public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX; private static final String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; public final OverlayPreferenceStore.OverlayKey[] fKeys= new OverlayPreferenceStore.OverlayKey[] { new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOREGROUND_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BACKGROUND_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.EDITOR_TAB_WIDTH), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_STRING_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STRING_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TASK_TAG_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_TAG_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MATCHING_BRACKETS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CURRENT_LINE), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_PRINT_MARGIN), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINK_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_PROBLEM_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WARNING_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TASK_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BOOKMARK_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_UNKNOWN_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CORRECTION_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_LINE_NUMBER_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SPACES_FOR_TABS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOACTIVATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOINSERT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_CASE_SENSITIVITY), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ADDIMPORT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_INSERT_COMPLETION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS), // new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FORMAT_JAVADOCS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_HOME_END), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER) }; private final String[][] fSyntaxColorListModel= new String[][] { { PreferencesMessages.getString("JavaEditorPreferencePage.multiLineComment"), PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.singleLineComment"), PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.strings"), PreferenceConstants.EDITOR_STRING_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaCommentTaskTags"), PreferenceConstants.EDITOR_TASK_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocLinks"), PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ }; private final String[][] fAppearanceColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), PreferenceConstants.EDITOR_CURRENT_LINE_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColor2"), PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.findScopeColor2"), PreferenceConstants.EDITOR_FIND_SCOPE_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkedPositionColor2"), PreferenceConstants.EDITOR_LINKED_POSITION_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR}, //$NON-NLS-1$ }; private final String[][] fAnnotationColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.annotations.errors"), PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, PreferenceConstants.EDITOR_PROBLEM_INDICATION, PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.annotations.warnings"), PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, PreferenceConstants.EDITOR_WARNING_INDICATION, PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.annotations.tasks"), PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, PreferenceConstants.EDITOR_TASK_INDICATION, PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.annotations.searchResults"), PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.annotations.bookmarks"), PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, PreferenceConstants.EDITOR_BOOKMARK_INDICATION, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.annotations.others"), PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, PreferenceConstants.EDITOR_UNKNOWN_INDICATION, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER } //$NON-NLS-1$ }; private final String[][] fContentAssistColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND } //$NON-NLS-1$ }; private OverlayPreferenceStore fOverlayStore; private JavaTextTools fJavaTextTools; private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; private Map fColorButtons= new HashMap(); private Map fCheckBoxes= new HashMap(); private SelectionListener fCheckBoxListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { Button button= (Button) e.widget; fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); } }; private Map fTextFields= new HashMap(); private ModifyListener fTextFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { Text text= (Text) e.widget; fOverlayStore.setValue((String) fTextFields.get(text), text.getText()); } }; private ArrayList fNumberFields= new ArrayList(); private ModifyListener fNumberFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { numberFieldChanged((Text) e.widget); } }; private List fSyntaxColorList; private List fAppearanceColorList; private List fContentAssistColorList; private List fAnnotationList; private ColorEditor fSyntaxForegroundColorEditor; private ColorEditor fAppearanceColorEditor; private ColorEditor fAnnotationForegroundColorEditor; private ColorEditor fContentAssistColorEditor; private ColorEditor fBackgroundColorEditor; private Button fBackgroundDefaultRadioButton; private Button fBackgroundCustomRadioButton; private Button fBackgroundColorButton; private Button fBoldCheckBox; private Button fAddJavaDocTagsButton; private Button fGuessMethodArgumentsButton; private SourceViewer fPreviewViewer; private Color fBackgroundColor; private Control fAutoInsertDelayText; private Control fAutoInsertJavaTriggerText; private Control fAutoInsertJavaDocTriggerText; private Button fShowInTextCheckBox; private Button fShowInOverviewRulerCheckBox; private Text fBrowserLikeLinksKeyModifierText; private Button fBrowserLikeLinksCheckBox; private StatusInfo fBrowserLikeLinksKeyModifierStatus; public JavaEditorPreferencePage() { setDescription(PreferencesMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys); } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); } private void handleSyntaxColorListSelection() { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fSyntaxForegroundColorEditor.setColorValue(rgb); fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); } private void handleAppearanceColorListSelection() { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAppearanceColorEditor.setColorValue(rgb); } private void handleContentAssistColorListSelection() { int i= fContentAssistColorList.getSelectionIndex(); String key= fContentAssistColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fContentAssistColorEditor.setColorValue(rgb); } private void handleAnnotationListSelection() { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAnnotationForegroundColorEditor.setColorValue(rgb); key= fAnnotationColorListModel[i][2]; fShowInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); key= fAnnotationColorListModel[i][3]; fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); } private Control createSyntaxPage(Composite parent) { Composite colorComposite= new Composite(parent, SWT.NULL); colorComposite.setLayout(new GridLayout()); Group backgroundComposite= new Group(colorComposite, SWT.SHADOW_ETCHED_IN); backgroundComposite.setLayout(new RowLayout()); backgroundComposite.setText(PreferencesMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ SelectionListener backgroundSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean custom= fBackgroundCustomRadioButton.getSelection(); fBackgroundColorButton.setEnabled(custom); fOverlayStore.setValue(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, !custom); } public void widgetDefaultSelected(SelectionEvent e) {} }; fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundDefaultRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundCustomRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundColorEditor= new ColorEditor(backgroundComposite); fBackgroundColorButton= fBackgroundColorEditor.getButton(); Label label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite editorComposite= new Composite(colorComposite, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); editorComposite.setLayoutData(gd); fSyntaxColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fSyntaxColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); label= new Label(stylesComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fSyntaxForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fBoldCheckBox= new Button(stylesComposite, SWT.CHECK); fBoldCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fBoldCheckBox.setLayoutData(gd); label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control previewer= createPreviewer(colorComposite); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(20); gd.heightHint= convertHeightInCharsToPixels(5); previewer.setLayoutData(gd); fSyntaxColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleSyntaxColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fSyntaxForegroundColorEditor.getColorValue()); } }); fBackgroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { PreferenceConverter.setValue(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, fBackgroundColorEditor.getColorValue()); } }); fBoldCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; fOverlayStore.setValue(key + BOLD, fBoldCheckBox.getSelection()); } }); return colorComposite; } private Control createPreviewer(Composite parent) { Preferences coreStore= createTemporaryCorePreferenceStore(); fJavaTextTools= new JavaTextTools(fOverlayStore, coreStore, false); fPreviewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); fPreviewViewer.configure(new JavaSourceViewerConfiguration(fJavaTextTools, null)); fPreviewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); fPreviewViewer.setEditable(false); initializeViewerColors(fPreviewViewer); String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ IDocument document= new Document(content); IDocumentPartitioner partitioner= fJavaTextTools.createDocumentPartitioner(); partitioner.connect(document); document.setDocumentPartitioner(partitioner); fPreviewViewer.setDocument(document); fOverlayStore.addPropertyChangeListener(new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String p= event.getProperty(); if (p.equals(PreferenceConstants.EDITOR_BACKGROUND_COLOR) || p.equals(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)) { initializeViewerColors(fPreviewViewer); } fPreviewViewer.invalidateTextPresentation(); } }); return fPreviewViewer.getControl(); } private Preferences createTemporaryCorePreferenceStore() { Preferences result= new Preferences(); result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$ return result; } /** * Initializes the given viewer's colors. * * @param viewer the viewer to be initialized */ private void initializeViewerColors(ISourceViewer viewer) { IPreferenceStore store= fOverlayStore; if (store != null) { StyledText styledText= viewer.getTextWidget(); // ---------- background color ---------------------- Color color= store.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR) ? null : createColor(store, PreferenceConstants.EDITOR_BACKGROUND_COLOR, styledText.getDisplay()); styledText.setBackground(color); if (fBackgroundColor != null) fBackgroundColor.dispose(); fBackgroundColor= color; } } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } // sets enabled flag for a control and all its sub-tree private static void setEnabled(Control control, boolean enable) { control.setEnabled(enable); if (control instanceof Composite) { Composite composite= (Composite) control; Control[] children= composite.getChildren(); for (int i= 0; i < children.length; i++) setEnabled(children[i], enable); } } private Control createAppearancePage(Composite parent) { Composite appearanceComposite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; appearanceComposite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ addTextField(appearanceComposite, label, PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ addTextField(appearanceComposite, label, PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.synchronizeOnCursor"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_OVERVIEW_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_CURRENT_LINE, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_PRINT_MARGIN, 0); Label l= new Label(appearanceComposite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(appearanceComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(appearanceComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fAppearanceColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fAppearanceColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fAppearanceColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fAppearanceColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAppearanceColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue()); } }); return appearanceComposite; } private Control createAnnotationsPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String text= PreferencesMessages.getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$ addCheckBox(composite, text, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); text= PreferencesMessages.getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ addCheckBox(composite, text, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); addFiller(composite); Label label= new Label(composite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationPresentationOptions")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; label.setLayoutData(gd); Composite editorComposite= new Composite(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAnnotationList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fAnnotationList.setLayoutData(gd); Composite optionsComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; optionsComposite.setLayout(layout); optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); fShowInTextCheckBox= new Button(optionsComposite, SWT.CHECK); fShowInTextCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInText")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fShowInTextCheckBox.setLayoutData(gd); fShowInOverviewRulerCheckBox= new Button(optionsComposite, SWT.CHECK); fShowInOverviewRulerCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fShowInOverviewRulerCheckBox.setLayoutData(gd); label= new Label(optionsComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fAnnotationForegroundColorEditor= new ColorEditor(optionsComposite); Button foregroundColorButton= fAnnotationForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fAnnotationList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAnnotationListSelection(); } }); fShowInTextCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][2]; fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection()); } }); fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][3]; fOverlayStore.setValue(key, fShowInOverviewRulerCheckBox.getSelection()); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAnnotationForegroundColorEditor.getColorValue()); } }); return composite; } private Control createTypingPage(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 1; composite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1); addFiller(composite); Group group= new Group(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; group.setLayout(layout); group.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ label= PreferencesMessages.getString("JavaEditorPreferencePage.wrapStrings"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.smartPaste"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeStrings"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBrackets"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBraces"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); //$NON-NLS-1$ Button button= addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.addJavaDocTags"); //$NON-NLS-1$ fAddJavaDocTagsButton= addCheckBox(group, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); createDependency(button, fAddJavaDocTagsButton); // label= PreferencesMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); //$NON-NLS-1$ // addCheckBox(group, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); return composite; } private void addFiller(Composite composite) { Label filler= new Label(composite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; filler.setLayoutData(gd); } private static void indent(Control control) { GridData gridData= new GridData(); gridData.horizontalIndent= 20; control.setLayoutData(gridData); } private static void createDependency(final Button master, final Control slave) { indent(slave); master.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) {} }); } private Control createContentAssistPage(Composite parent) { Composite contentAssistComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; contentAssistComposite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOINSERT, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ADDIMPORT, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.insertCompletion"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_INSERT_COMPLETION, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ Button button= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ fGuessMethodArgumentsButton= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0); createDependency(button, fGuessMethodArgumentsButton); label= PreferencesMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$ final Button autoactivation= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION, 0); autoactivation.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { updateAutoactivationControls(); } }); label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$ fAutoInsertDelayText= addTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 4, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$ fAutoInsertJavaTriggerText= addTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, 4, 0, false); label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$ fAutoInsertJavaDocTriggerText= addTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, 4, 0, false); Label l= new Label(contentAssistComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.colorOptions")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(contentAssistComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fContentAssistColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fContentAssistColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fContentAssistColorEditor= new ColorEditor(stylesComposite); Button colorButton= fContentAssistColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; colorButton.setLayoutData(gd); fContentAssistColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleContentAssistColorListSelection(); } }); colorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fContentAssistColorList.getSelectionIndex(); String key= fContentAssistColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fContentAssistColorEditor.getColorValue()); } }); return contentAssistComposite; } private Control createNavigationPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String text= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); //$NON-NLS-1$ fBrowserLikeLinksCheckBox= addCheckBox(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean state= fBrowserLikeLinksCheckBox.getSelection(); fBrowserLikeLinksKeyModifierText.setEnabled(state); handleBrowserLikeLinksKeyModifierModified(); } public void widgetDefaultSelected(SelectionEvent e) { } }); // Text field for modifier string text= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); //$NON-NLS-1$ fBrowserLikeLinksKeyModifierText= addTextField(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, 0, false); fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { private boolean isModifierCandidate; public void keyPressed(KeyEvent e) { isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0; } public void keyReleased(KeyEvent e) { if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { String text= fBrowserLikeLinksKeyModifierText.getText(); if (text.length() > 0) text= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.appendModifier", new String[] {text, Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else text= Action.findModifierString(e.stateMask); fBrowserLikeLinksKeyModifierText.setText(text); fBrowserLikeLinksKeyModifierText.setSelection(text.length(), text.length()); } } }); fBrowserLikeLinksKeyModifierText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleBrowserLikeLinksKeyModifierModified(); } }); return composite; } private void handleBrowserLikeLinksKeyModifierModified() { String modifiers= fBrowserLikeLinksKeyModifierText.getText(); int stateMask= computeStateMask(modifiers); if (fBrowserLikeLinksCheckBox.getSelection() && stateMask == -1) { fBrowserLikeLinksKeyModifierStatus= new StatusInfo(StatusInfo.ERROR, PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ setValid(false); StatusUtil.applyToStatusLine(this, fBrowserLikeLinksKeyModifierStatus); } else { fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); updateStatus(fBrowserLikeLinksKeyModifierStatus); } } private IStatus getBrowserLikeLinksKeyModifierStatus() { if (fBrowserLikeLinksKeyModifierStatus == null) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); return fBrowserLikeLinksKeyModifierStatus; } /** * Computes the state mask for the given modifier string. * * @param modifiers the string with the modifiers, separated by '+', '-', ';', ',' or '.' * @return the state mask or -1 if the input is invalid */ private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= Action.findModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { fOverlayStore.load(); fOverlayStore.start(); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); TabItem item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ item.setControl(createAppearancePage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ item.setControl(createSyntaxPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist")); //$NON-NLS-1$ item.setControl(createContentAssistPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationsTab.title")); //$NON-NLS-1$ item.setControl(createAnnotationsPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle")); //$NON-NLS-1$ item.setControl(createTypingPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.hoverTab.title")); //$NON-NLS-1$ fJavaEditorHoverConfigurationBlock= new JavaEditorHoverConfigurationBlock(this, fOverlayStore); item.setControl(fJavaEditorHoverConfigurationBlock.createControl(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.navigationTab.title")); //$NON-NLS-1$ item.setControl(createNavigationPage(folder)); initialize(); return folder; } private void initialize() { initializeFields(); for (int i= 0; i < fSyntaxColorListModel.length; i++) fSyntaxColorList.add(fSyntaxColorListModel[i][0]); fSyntaxColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) { fSyntaxColorList.select(0); handleSyntaxColorListSelection(); } } }); for (int i= 0; i < fAppearanceColorListModel.length; i++) fAppearanceColorList.add(fAppearanceColorListModel[i][0]); fAppearanceColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); } } }); for (int i= 0; i < fAnnotationColorListModel.length; i++) fAnnotationList.add(fAnnotationColorListModel[i][0]); fAnnotationList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAnnotationList != null && !fAnnotationList.isDisposed()) { fAnnotationList.select(0); handleAnnotationListSelection(); } } }); for (int i= 0; i < fContentAssistColorListModel.length; i++) fContentAssistColorList.add(fContentAssistColorListModel[i][0]); fContentAssistColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fContentAssistColorList != null && !fContentAssistColorList.isDisposed()) { fContentAssistColorList.select(0); handleContentAssistColorListSelection(); } } }); } private void initializeFields() { Iterator e= fColorButtons.keySet().iterator(); while (e.hasNext()) { ColorEditor c= (ColorEditor) e.next(); String key= (String) fColorButtons.get(c); RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); c.setColorValue(rgb); } e= fCheckBoxes.keySet().iterator(); while (e.hasNext()) { Button b= (Button) e.next(); String key= (String) fCheckBoxes.get(b); b.setSelection(fOverlayStore.getBoolean(key)); } e= fTextFields.keySet().iterator(); while (e.hasNext()) { Text t= (Text) e.next(); String key= (String) fTextFields.get(t); t.setText(fOverlayStore.getString(key)); } RGB rgb= PreferenceConverter.getColor(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR); fBackgroundColorEditor.setColorValue(rgb); boolean default_= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); fBackgroundDefaultRadioButton.setSelection(default_); fBackgroundCustomRadioButton.setSelection(!default_); fBackgroundColorButton.setEnabled(!default_); boolean closeJavaDocs= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS); fAddJavaDocTagsButton.setEnabled(closeJavaDocs); boolean fillMethodArguments= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES); fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); updateAutoactivationControls(); } private void updateAutoactivationControls() { boolean autoactivation= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); fAutoInsertDelayText.setEnabled(autoactivation); fAutoInsertJavaTriggerText.setEnabled(autoactivation); fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); } /* * @see PreferencePage#performOk() */ public boolean performOk() { fJavaEditorHoverConfigurationBlock.performOk(); fOverlayStore.propagate(); JavaPlugin.getDefault().savePluginPreferences(); return true; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fOverlayStore.loadDefaults(); initializeFields(); handleSyntaxColorListSelection(); handleAppearanceColorListSelection(); handleAnnotationListSelection(); handleContentAssistColorListSelection(); fJavaEditorHoverConfigurationBlock.performDefaults(); super.performDefaults(); fPreviewViewer.invalidateTextPresentation(); } /* * @see DialogPage#dispose() */ public void dispose() { if (fJavaTextTools != null) { fJavaTextTools.dispose(); fJavaTextTools= null; } if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) fBackgroundColor.dispose(); super.dispose(); } private Button addCheckBox(Composite parent, String label, String key, int indentation) { Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; gd.horizontalSpan= 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); fCheckBoxes.put(checkBox, key); return checkBox; } private Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { Label labelControl= new Label(composite, SWT.NONE); labelControl.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; labelControl.setLayoutData(gd); Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE); gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.widthHint= convertWidthInCharsToPixels(textLimit + 1); textControl.setLayoutData(gd); textControl.setTextLimit(textLimit); fTextFields.put(textControl, key); if (isNumber) { fNumberFields.add(textControl); textControl.addModifyListener(fNumberFieldListener); } else { textControl.addModifyListener(fTextFieldListener); } return textControl; } private String loadPreviewContentFromFile(String filename) { String line; String separator= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(512); BufferedReader reader= null; try { reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); while ((line= reader.readLine()) != null) { buffer.append(line); buffer.append(separator); } } catch (IOException io) { JavaPlugin.log(io); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) {} } } return buffer.toString(); } private void numberFieldChanged(Text textControl) { String number= textControl.getText(); IStatus status= validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) fOverlayStore.setValue((String) fTextFields.get(textControl), number); updateStatus(status); } private IStatus validatePositiveNumber(String number) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value < 0) status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } catch (NumberFormatException e) { status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } void updateStatus(IStatus status) { if (!status.matches(IStatus.ERROR)) { for (int i= 0; i < fNumberFields.size(); i++) { Text text= (Text) fNumberFields.get(i); IStatus s= validatePositiveNumber(text.getText()); status= StatusUtil.getMoreSevere(s, status); } } status= StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), status); status= StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), status); setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } }
30,941
Bug 30941 Preferences default initialization. Can not do a syncExec
20030204 The initialization of the preference default currently contains a final Display display= Display.getDefault(); display.syncExec(new Runnable() { public void run() { Color c= display.getSystemColor(SWT.COLOR_GRAY); rgbs[0]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND); rgbs[1]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); rgbs[2]= c.getRGB(); } }); We should avoid and remove this as this is a candidate for a deadlock.
resolved fixed
45418a9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T18:46:22Z
2003-02-05T10:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.action.Action; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.ui.text.IJavaColorConstants; /** * Preference constants used in the JDT-UI preference store. Clients should only read the * JDT-UI preference store using these values. Clients are not allowed to modify the * preference store programmatically. * * @since 2.0 */ public class PreferenceConstants { private PreferenceConstants() { } /** * A named preference that controls return type rendering of methods in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> return types * are rendered * </p> */ public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.jdt.ui.methodreturntype";//$NON-NLS-1$ /** * A named preference that controls if override indicators are rendered in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> override * indicators are rendered * </p> */ public static final String APPEARANCE_OVERRIDE_INDICATOR= "org.eclipse.jdt.ui.overrideindicator";//$NON-NLS-1$ /** * A named preference that defines the pattern used for package name compression. * <p> * Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern * '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'. * </p> */ public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$ /** * A named preference that controls if package name compression is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW */ public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$ /** * A named preference that controls if empty inner packages are folded in * the hierarchical mode of the package explorer. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> empty * inner packages are folded. * </p> * @since 2.1 */ public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$ /** * A named preference that defines how member elements are ordered by the * Java views using the <code>JavaElementSorter</code>. * <p> * Value is of type <code>String</code>: A comma separated list of the * following entries. Each entry must be in the list, no duplication. List * order defines the sort order. * <ul> * <li><b>T</b>: Types</li> * <li><b>C</b>: Constructors</li> * <li><b>I</b>: Initializers</li> * <li><b>M</b>: Methods</li> * <li><b>F</b>: Fields</li> * <li><b>SI</b>: Static Initializers</li> * <li><b>SM</b>: Static Methods</li> * <li><b>SF</b>: Static Fields</li> * </ul> * </p> * @since 2.1 */ public static final String APPEARANCE_MEMBER_SORT_ORDER= "outlinesortoption"; //$NON-NLS-1$ /** * A named preference that controls if prefix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of prefixes to be removed from a local variable to compute setter * and gettter names. * <p> * Value is of type <code>String</code>: comma separated list of prefixed * </p> * * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$ /** * A named preference that controls if suffix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of suffixes to be removed from a local variable to compute setter * and getter names. * <p> * Value is of type <code>String</code>: comma separated list of suffixes * </p> * @deprecated Use setting from JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_SUFFIXES and CODEASSIST_STATIC_FIELD_SUFFIXES) */ public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ /** * A named preference that controls if comment stubs will be added * automatically to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$ /** * A named preference that controls if a comment stubs will be added * automatocally to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precice). */ public static final String CODEGEN__JAVADOC_STUBS= CODEGEN_ADD_COMMENTS; /** * A named preference that controls if a non-javadoc comment gets added to methods generated via the * "Override Methods" operation. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the overriding method comment. */ public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$ /** * A named preference that controls if a file comment gets added to newly created files. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the new type code template. */ public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$ /** * A named preference that holds a list of comma separated package names. The list specifies the import order used by * the "Organize Imports" opeation. * <p> * Value is of type <code>String</code>: semicolon separated list of package * names * </p> */ public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.jdt.ui.importorder"; //$NON-NLS-1$ /** * A named preference that specifies the number of imports added before a star-import declaration is used. * <p> * Value is of type <code>Int</code>: positive value specifing the number of non star-import is used * </p> */ public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.jdt.ui.ondemandthreshold"; //$NON-NLS-1$ /** * A named preferences that controls if types that start with a lower case letters get added by the * "Organize Import" operation. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.jdt.ui.ignorelowercasenames"; //$NON-NLS-1$ /** * A named preference that speficies whether children of a compilation unit are shown in the package explorer. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String SHOW_CU_CHILDREN= "org.eclipse.jdt.ui.packages.cuchildren"; //$NON-NLS-1$ /** * A named preference that controls whether the package explorer's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the hierarchy view's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_TYPEHIERARCHY_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the projects view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PROJECTS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.projectstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the packages view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.packagestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the types view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_TYPES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.typestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the members view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_MEMBERS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.memberstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether new projects are generated using source and output folder. * <p> * Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and * output folder. If <code>false</code> source and output folder equals to the project. * </p> */ public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ /** * A named preference that specifies the source folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ /** * A named preference that specifies the output folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ /** * A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library * consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the * JRE on the new project's classpath. * <p> * Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries. * <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients * should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string * and the methods <code>decodeJRELibraryDescription(String)</code> and <code> * decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array * of classpath entries from an encoded string. * </p> * * @see #NEWPROJECT_JRELIBRARY_INDEX * @see #encodeJRELibrary(String, IClasspathEntry[]) * @see #decodeJRELibraryDescription(String) * @see #decodeJRELibraryClasspathEntries(String) */ public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$ /** * A named preferences that specifies the current active JRE library. * <p> * Value is of type <code>Int</code>: an index into the list of possible JRE libraries. * </p> * * @see #NEWPROJECT_JRELIBRARY_LIST */ public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$ /** * A named preference that controls if a new type hierarchy gets opened in a * new type hierarchy perspective or inside the type hierarchy view part. * <p> * Value is of type <code>String</code>: possible values are <code> * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code> * OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>. * </p> * * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART */ public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$ /** * A named preference that controls the behaviour when double clicking on a container in the packages view. * <p> * Value is of type <code>String</code>: possible values are <code> * DOUBLE_CLICK_GOES_INTO</code> or <code> * DOUBLE_CLICK_EXPANDS</code>. * </p> * * @see #DOUBLE_CLICK_EXPANDS * @see #DOUBLE_CLICK_GOES_INTO */ public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$ /** * A named preference that controls whether Java views update their presentation while editing or when saving the * content of an editor. * <p> * Value is of type <code>String</code>: possible values are <code> * UPDATE_ON_SAVE</code> or <code> * UPDATE_WHILE_EDITING</code>. * </p> * * @see #UPDATE_ON_SAVE * @see #UPDATE_WHILE_EDITING */ public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$ /** * A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard. * <p> * Value is of type <code>String</code>. * </p> */ public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when no control key is * pressed. * * @see JavaUI * @since 2.1 */ public static final String EDITOR_TEXT_HOVER_MODIFIERS= "hoverModifiers"; //$NON-NLS-1$ /** * A named preference that controls whether bracket matching highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight matching brackets. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$ /** * A named preference that controls whether the current line highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight the current line. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$ /** * A named preference that controls whether the print margin is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$ /** * A named preference that holds the color used to render the print margin. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$ /** * Print margin column. Int value. */ public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$ /** * A named preference that holds the color used for the find/replace scope. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; /** * A named preference that specifies if the editor uses spaces for tabs. * <p> * Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used * in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab * key. * </p> */ public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$ /** * A named preference that holds the number of spaces used per tab in the editor. * <p> * Value is of type <code>Int</code>: positive int value specifying the number of * spaces per tab. * </p> */ public final static String EDITOR_TAB_WIDTH= "org.eclipse.jdt.ui.editor.tab.width"; //$NON-NLS-1$ /** * A named preference that controls whether the outline view selection * should stay in sync with with the element at the current cursor position. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ /** * A named preference that controls if correction indicators are shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows problem indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render problem indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_PROBLEM_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$ /**PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; * A named preference that controls whether the editor shows warning indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render warning indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_WARNING_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows task indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render task indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_TASK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows bookmark * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render bookmark indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_BOOKMARK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows search * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render search indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_SEARCH_RESULT_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows unknown * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render unknown * indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_UNKNOWN_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows error * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows warning * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows task * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * bookmark indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * search result indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * unknown indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close strings' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'wrap strings' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close brackets' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close braces' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close java docs' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'add JavaDoc tags' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$ /** * A named preference that controls whether the 'format Javadoc tags' * feature is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_FORMAT_JAVADOCS= "autoFormatJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart paste' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart home-end' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; /** * A named preference that controls if temporary problems are evaluated and shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$ /** * A named preference that controls if the overview ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$ /** * A named preference that controls if the line number ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$ /** * A named preference that holds the color used to render line numbers inside the line number ruler. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @see #EDITOR_LINE_NUMBER_RULER */ public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$ /** * A named preference that holds the color used to render linked positions inside code templates. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$ /** * A named preference that holds the color used as the text foreground. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; /** * A named preference that describes if the system default foreground color * is used as the text foreground. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; /** * A named preference that holds the color used as the text background. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; /** * A named preference that describes if the system default background color * is used as the text foreground. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; /** * Preference key suffix for bold text style preference keys. */ public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$ /** * A named preference that holds the color used to render multi line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT; /** * The symbolic font name for the Java editor text font * (value <code>"org.eclipse.jdt.ui.editors.textfont"</code>). * * @since 2.1 */ public final static String EDITOR_TEXT_FONT= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$ /** * A named preference that controls whether multi line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render single line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT; /** * A named preference that controls whether sinle line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD; /** * A named preference that controls whether keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render string constants. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING; /** * A named preference that controls whether string constants are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT; /** * A named preference that controls whether Java default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render task tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_TASK_TAG_COLOR= IJavaColorConstants.TASK_TAG; /** * A named preference that controls whether task tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_TASK_TAG_BOLD= IJavaColorConstants.TASK_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD; /** * A named preference that controls whether javadoc keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG; /** * A named preference that controls whether javadoc tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc links. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK; /** * A named preference that controls whether javadoc links are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT; /** * A named preference that controls whether javadoc default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used for 'linked-mode' underline. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$ /** * A named preference that controls whether hover tooltips in the editor are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when no control key is * pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS} */ public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS} */ public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>SHIFT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS} */ public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will be removed in one of the next builds. */ public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>ALT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code>, * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that no hover should be shown for the given key modifiers. * @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that the default hover should be shown for the given key * modifiers. The default hover is described by the * <code>EDITOR_DEFAULT_HOVER</code> property. * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$ /** * A named preference that defines the hover named the 'default hover'. * Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$ /** * A named preference that controls if segmented view (show selected element only) is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$ /** * A named preference that controls if browser like links are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_BROWSER_LIKE_LINKS= "browserLikeLinks"; //$NON-NLS-1$ /** * A named preference that controls the key modifier for browser like links. * <p> * Value is of type <code>String</code>. * </p> */ public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER= "browserLikeLinksKeyModifier"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist gets auto activated. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$ /** * A name preference that holds the auto activation delay time in milli seconds. * <p> * Value is of type <code>Int</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$ /** * A named preference that controls if code assist contains only visible proposals. * <p> * Value is of type <code>Boolean</code>. if <code>true<code> code assist only contains visible members. If * <code>false</code> all members are included. * </p> */ public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist inserts a * proposal automatically if only one proposal is available. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist adds import * statements. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist only inserts * completions. If set to false the proposals can also _replace_ code. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$ /** * A named preference that controls whether code assist proposals filtering is case sensitive or not. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$ /** * A named preference that defines if code assist proposals are sorted in alphabetical order. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical * order. If <code>false</code> that are unsorted. * </p> */ public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$ /** * A named preference that controls if argument names are filled in when a method is selected from as list * of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$ /** * A named preference that controls if method arguments are guessed when a * method is selected from as list of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Java code. * <p> * Value is of type <code>Sring</code>. All characters that trigger auto code assist in Java code. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Javadoc. * <p> * Value is of type <code>Sring</code>. All characters that trigger auto code assist in Javadoc. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used for parameter hints. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ /** * A named preference that controls the behaviour of the refactoring wizard for showing the error page. * <p> * Value is of type <code>String</code>. Valid values are: * <code>REFACTOR_FATAL_SEVERITY</code>, * <code>REFACTOR_ERROR_SEVERITY</code>, * <code>REFACTOR_WARNING_SEVERITY</code> * <code>REFACTOR_INFO_SEVERITY</code>, * <code>REFACTOR_OK_SEVERITY</code>. * </p> * * @see #REFACTOR_FATAL_SEVERITY * @see #REFACTOR_ERROR_SEVERITY * @see #REFACTOR_WARNING_SEVERITY * @see #REFACTOR_INFO_SEVERITY * @see #REFACTOR_OK_SEVERITY */ public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$ /** * A named preference thet controls whether all dirty editors are automatically saved before a refactoring is * executed. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$ /** * A named preference that controls if the Java Browsing views are linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #LINK_PACKAGES_TO_EDITOR */ public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls the layout of the Java Browsing views vertically. Boolean value. * <p> * Value is of type <code>Boolean</code>. If <code>true<code> the views are stacked vertical. * If <code>false</code> they are stacked horizontal. * </p> */ public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.jdt.ui.browsing.stackVertically"; //$NON-NLS-1$ /** * A named preference that controls if templates are formatted when applied. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 2.1 */ public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.jdt.ui.template.format"; //$NON-NLS-1$ public static void initializeDefaultValues(IPreferenceStore store) { store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); // JavaBasePreferencePage store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, false); store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false); store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS); store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING); store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true); // AppearancePreferencePage store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false); store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true); store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$ store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true); // ImportOrganizePreferencePage store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); // ClasspathVariablesPreferencePage // CodeFormatterPreferencePage // CompilerPreferencePage // no initialization needed // RefactoringPreferencePage store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY); store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); // TemplatePreferencePage store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); // CodeGenerationPreferencePage // compatibility code if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) { String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); if (prefix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, prefix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); } } if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) { String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); if (suffix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); } } store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); // MembersOrderPreferencePage store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SI,SF,SM,I,F,C,M"); //$NON-NLS-1$ // must add here to guarantee that it is the first in the listener list store.addPropertyChangeListener(JavaPlugin.getDefault().getMemberOrderPreferenceCache()); // JavaEditorPreferencePage /* * Ensure that the display is accessed only in the UI thread. * Ensure that there are no side effects of switching the thread. */ final RGB[] rgbs= new RGB[3]; final Display display= Display.getDefault(); display.syncExec(new Runnable() { public void run() { Color c= display.getSystemColor(SWT.COLOR_GRAY); rgbs[0]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND); rgbs[1]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); rgbs[2]= c.getRGB(); } }); store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, rgbs[0]); store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224)); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180)); store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0 , 128)); store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, 200 , 45)); store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, 255)); store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, 164, 99)); store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new RGB(192, 192, 192)); store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true); store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, false); store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true); store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200 , 100)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgbs[1]); store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgbs[2]); store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500); store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true); store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false); store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true); store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false); store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true); store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); String ctrl= Action.findModifierString(SWT.CTRL); store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, "Ctrl"); //$NON-NLS-1$ // do more complicated stuff NewJavaProjectPreferencePage.initDefaults(store); } /** * Returns the JDT-UI preference store. * * @return the JDT-UI preference store */ public static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /** * Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>. * * @param description a string value describing the JRE library. The description is used * to indentify the JDR library in the UI * @param entries an array of classpath entries to be encoded * * @return the encoded string. */ public static String encodeJRELibrary(String description, IClasspathEntry[] entries) { return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries); } /** * Decodes an encoded JRE library and returns its description string. * * @return the description of an encoded JRE library * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static String decodeJRELibraryDescription(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); } /** * Decodes an encoded JRE library and returns its classpath entries. * * @return the array of classpath entries of an encoded JRE library. * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); } /** * Returns the current configuration for the JRE to be used as default in new Java projects. * This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST * </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>. * * @return the current default set of classpath entries * * @see #NEWPROJECT_JRELIBRARY_LIST * @see #NEWPROJECT_JRELIBRARY_INDEX */ public static IClasspathEntry[] getDefaultJRELibrary() { return NewJavaProjectPreferencePage.getDefaultJRELibrary(); } }
31,957
Bug 31957 Refactor/move doesn't remember non-java files
When refactoring with "rename", the list of non-java files is remembered from use to use. When using "move", the previous settings are ignored, and the last "rename" settings are used. This is based on the M5 build.
resolved fixed
5138d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:07:56Z
2003-02-15T23:00:00Z
org.eclipse.jdt.ui/ui
31,957
Bug 31957 Refactor/move doesn't remember non-java files
When refactoring with "rename", the list of non-java files is remembered from use to use. When using "move", the previous settings are ignored, and the last "rename" settings are used. This is based on the M5 build.
resolved fixed
5138d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:07:56Z
2003-02-15T23:00:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/QualifiedNameComponent.java
31,957
Bug 31957 Refactor/move doesn't remember non-java files
When refactoring with "rename", the list of non-java files is remembered from use to use. When using "move", the previous settings are ignored, and the last "rename" settings are used. This is based on the M5 build.
resolved fixed
5138d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:07:56Z
2003-02-15T23:00:00Z
org.eclipse.jdt.ui/ui
31,957
Bug 31957 Refactor/move doesn't remember non-java files
When refactoring with "rename", the list of non-java files is remembered from use to use. When using "move", the previous settings are ignored, and the last "rename" settings are used. This is based on the M5 build.
resolved fixed
5138d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:07:56Z
2003-02-15T23:00:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameInputWizardPage.java
31,957
Bug 31957 Refactor/move doesn't remember non-java files
When refactoring with "rename", the list of non-java files is remembered from use to use. When using "move", the previous settings are ignored, and the last "rename" settings are used. This is based on the M5 build.
resolved fixed
5138d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:07:56Z
2003-02-15T23:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/SelectionTransferDropAdapter.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ 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.DropTargetEvent; import org.eclipse.swt.dnd.Transfer; 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.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.DialogSettings; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery; import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.SourceReferenceUtil; import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; 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; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.QualifiedNameComponent; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardPage; import org.eclipse.jdt.internal.ui.reorg.ReorgQueries; import org.eclipse.jdt.internal.ui.reorg.DeleteSourceReferencesAction; import org.eclipse.jdt.internal.ui.reorg.JdtCopyAction; import org.eclipse.jdt.internal.ui.reorg.JdtMoveAction; import org.eclipse.jdt.internal.ui.reorg.MockWorkbenchSite; import org.eclipse.jdt.internal.ui.reorg.ReorgActionFactory; import org.eclipse.jdt.internal.ui.reorg.ReorgMessages; import org.eclipse.jdt.internal.ui.reorg.SimpleSelectionProvider; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.ui.actions.SelectionDispatchAction; public class SelectionTransferDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener { private List fElements; private MoveRefactoring fMoveRefactoring; private int fCanMoveElements; private CopyRefactoring fCopyRefactoring; private int fCanCopyElements; private ISelection fSelection; private AddMethodStubAction fAddMethodStubAction; private static final int DROP_TIME_DIFF_TRESHOLD= 150; public SelectionTransferDropAdapter(StructuredViewer viewer) { super(viewer, DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND); fAddMethodStubAction= new AddMethodStubAction(); } //---- TransferDropTargetListener interface --------------------------------------- public Transfer getTransfer() { return LocalSelectionTransfer.getInstance(); } //---- Actual DND ----------------------------------------------------------------- public void dragEnter(DropTargetEvent event) { clear(); super.dragEnter(event); } public void dragLeave(DropTargetEvent event) { clear(); super.dragLeave(event); } private void clear() { fElements= null; fSelection= null; fMoveRefactoring= null; fCanMoveElements= 0; fCopyRefactoring= null; fCanCopyElements= 0; } public void validateDrop(Object target, DropTargetEvent event, int operation) { event.detail= DND.DROP_NONE; if (tooFast(event)) return; initializeSelection(); try { if (operation == DND.DROP_DEFAULT) { event.detail= handleValidateDefault(target, event); } else if (operation == DND.DROP_COPY) { event.detail= handleValidateCopy(target, event); } else if (operation == DND.DROP_MOVE) { event.detail= handleValidateMove(target, event); } else if (operation == DND.DROP_LINK) { event.detail= handleValidateLink(target, event); } } catch (JavaModelException e){ ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ event.detail= DND.DROP_NONE; } } protected void initializeSelection(){ if (fElements != null) return; ISelection s= LocalSelectionTransfer.getInstance().getSelection(); if (!(s instanceof IStructuredSelection)) return; fSelection= s; fElements= ((IStructuredSelection)s).toList(); } protected ISelection getSelection(){ return fSelection; } private boolean tooFast(DropTargetEvent event) { return Math.abs(LocalSelectionTransfer.getInstance().getSelectionSetTime() - event.time) < DROP_TIME_DIFF_TRESHOLD; } public void drop(Object target, DropTargetEvent event) { try{ if (event.detail == DND.DROP_MOVE) { handleDropMove(target, event); if (! canPasteSourceReferences(target)) return; DeleteSourceReferencesAction delete= ReorgActionFactory.createDeleteSourceReferencesAction(getDragableSourceReferences()); delete.setAskForDeleteConfirmation(true); delete.setCanDeleteGetterSetter(false); delete.update(delete.getSelection()); if (delete.isEnabled()) delete.run(); } else if (event.detail == DND.DROP_COPY) { handleDropCopy(target, event); } else if (event.detail == DND.DROP_LINK) { handleDropLink(target, event); } } catch (JavaModelException e){ ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ } finally{ // The drag source listener must not perform any operation // since this drop adapter did the remove of the source even // if we moved something. event.detail= DND.DROP_NONE; } } private int handleValidateDefault(Object target, DropTargetEvent event) throws JavaModelException{ if (target == null) return DND.DROP_NONE; if (canPasteSourceReferences(target)) return handleValidateCopy(target, event); else return handleValidateMove(target, event); } private int handleValidateMove(Object target, DropTargetEvent event) throws JavaModelException{ if (target == null) return DND.DROP_NONE; if (canPasteSourceReferences(target)){ if (canMoveSelectedSourceReferences(target)) return DND.DROP_MOVE; else return DND.DROP_NONE; } if (fMoveRefactoring == null){ IPackageFragmentRootManipulationQuery query= JdtMoveAction.createUpdateClasspathQuery(getViewer().getControl().getShell()); fMoveRefactoring= new MoveRefactoring(fElements, JavaPreferencesSettings.getCodeGenerationSettings(), query); } if (!canMoveElements()) return DND.DROP_NONE; if (fMoveRefactoring.isValidDestination(target)) return DND.DROP_MOVE; else return DND.DROP_NONE; } private boolean canMoveElements() { if (fCanMoveElements == 0) { fCanMoveElements= 2; if (! canActivate(fMoveRefactoring)) fCanMoveElements= 1; } return fCanMoveElements == 2; } private boolean canActivate(ReorgRefactoring ref){ try{ return ref.checkActivation(new NullProgressMonitor()).isOK(); } catch(JavaModelException e){ ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ return false; } } private void handleDropLink(Object target, DropTargetEvent event) { if (fAddMethodStubAction.init((IType)target, getSelection())) fAddMethodStubAction.run(); } private int handleValidateLink(Object target, DropTargetEvent event) { if (target instanceof IType && AddMethodStubAction.canActionBeAdded((IType)target, getSelection())) return DND.DROP_LINK; else return DND.DROP_NONE; } private void handleDropMove(final Object target, DropTargetEvent event) throws JavaModelException{ if (canPasteSourceReferences(target)){ pasteSourceReferences(target, event); return; } new DragNDropMoveAction(new SimpleSelectionProvider(fElements), target).run(); } private void pasteSourceReferences(final Object target, DropTargetEvent event) { SelectionDispatchAction pasteAction= ReorgActionFactory.createPasteAction(getDragableSourceReferences(), target); pasteAction.update(pasteAction.getSelection()); if (!pasteAction.isEnabled()){ event.detail= DND.DROP_NONE; return; } pasteAction.run(); return; } private int handleValidateCopy(Object target, DropTargetEvent event) throws JavaModelException{ if (canPasteSourceReferences(target)) return DND.DROP_COPY; if (fCopyRefactoring == null){ IPackageFragmentRootManipulationQuery query= JdtCopyAction.createUpdateClasspathQuery(getViewer().getControl().getShell()); fCopyRefactoring= new CopyRefactoring(fElements, new ReorgQueries(), query); } if (!canCopyElements()) return DND.DROP_NONE; if (fCopyRefactoring.isValidDestination(target)) return DND.DROP_COPY; else return DND.DROP_NONE; } private boolean canMoveSelectedSourceReferences(Object target) throws JavaModelException{ ICompilationUnit targetCu= getCompilationUnit(target); if (targetCu == null) return false; ISourceReference[] elements= getDragableSourceReferences(); for (int i= 0; i < elements.length; i++) { if (targetCu.equals(SourceReferenceUtil.getCompilationUnit(elements[i]))) return false; } return true; } private static ICompilationUnit getCompilationUnit(Object target){ if (target instanceof ISourceReference) return SourceReferenceUtil.getCompilationUnit((ISourceReference)target); else return null; } private boolean canPasteSourceReferences(Object target) throws JavaModelException{ ISourceReference[] elements= getDragableSourceReferences(); if (elements.length != fElements.size()) return false; SelectionDispatchAction pasteAction= ReorgActionFactory.createPasteAction(elements, target); pasteAction.update(pasteAction.getSelection()); return pasteAction.isEnabled(); } private ISourceReference[] getDragableSourceReferences(){ List result= new ArrayList(fElements.size()); for(Iterator iter= fElements.iterator(); iter.hasNext();){ Object each= iter.next(); if (isDragableSourceReferences(each)) result.add(each); } return (ISourceReference[])result.toArray(new ISourceReference[result.size()]); } private static boolean isDragableSourceReferences(Object element) { if (!(element instanceof ISourceReference)) return false; if (!(element instanceof IJavaElement)) return false; if (element instanceof ICompilationUnit) return false; return true; } private boolean canCopyElements() { if (fCanCopyElements == 0) { fCanCopyElements= 2; if (!canActivate(fCopyRefactoring)) fCanCopyElements= 1; } return fCanCopyElements == 2; } private void handleDropCopy(final Object target, DropTargetEvent event) throws JavaModelException{ if (canPasteSourceReferences(target)){ pasteSourceReferences(target, event); return; } SelectionDispatchAction action= ReorgActionFactory.createDnDCopyAction(fElements, ResourceUtil.getResource(target)); action.run(); } //-- private static class DragNDropMoveAction extends JdtMoveAction{ private Object fTarget; private static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1; public DragNDropMoveAction(ISelectionProvider provider, Object target){ super(new MockWorkbenchSite(provider)); Assert.isNotNull(target); fTarget= target; } protected Object selectDestination(ReorgRefactoring ref) { return fTarget; } protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException { if (!super.isOkToProceed(refactoring)) return false; return askIfUpdateReferences((MoveRefactoring)refactoring); } //returns false iff canceled or error private boolean askIfUpdateReferences(MoveRefactoring ref) throws JavaModelException { if (! ref.canUpdateReferences() && !ref.canUpdateQualifiedNames()) { setShowPreview(false); return true; } switch (showMoveDialog(ref)){ case IDialogConstants.CANCEL_ID: setShowPreview(false); return false; case IDialogConstants.OK_ID: setShowPreview(false); return true; case PREVIEW_ID: setShowPreview(true); return true; default: Assert.isTrue(false); //not expected to get here return false; } } private static int showMoveDialog(MoveRefactoring ref) { Shell shell= JavaPlugin.getActiveWorkbenchShell().getShell(); final UpdateDialog dialog= new UpdateDialog(shell, ref); shell.getDisplay().syncExec(new Runnable() { public void run() { dialog.open(); } }); return dialog.getReturnCode(); } private static class UpdateDialog extends Dialog { private Button fPreview; private MoveRefactoring fRefactoring; private Button fReferenceCheckbox; private Button fQualifiedNameCheckbox; private QualifiedNameComponent fQualifiedNameComponent; public UpdateDialog(Shell parentShell, MoveRefactoring refactoring) { super(parentShell); fRefactoring= refactoring; } protected void configureShell(Shell shell) { shell.setText(PackagesMessages.getString("SelectionTransferDropAdapter.dialog.title")); //$NON-NLS-1$ super.configureShell(shell); } protected void createButtonsForButtonBar(Composite parent) { fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$ super.createButtonsForButtonBar(parent); } protected void buttonPressed(int buttonId) { if (buttonId == PREVIEW_ID) { setReturnCode(PREVIEW_ID); close(); } else { super.buttonPressed(buttonId); } } protected Control createDialogArea(Composite parent) { Composite result= (Composite)super.createDialogArea(parent); addUpdateReferenceComponent(result); addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth); return result; } private void updateButtons() { Button okButton= getButton(IDialogConstants.OK_ID); boolean okEnabled= true; // we keep this since the code got copied from JdtMoveAction. okButton.setEnabled(okEnabled); fReferenceCheckbox.setEnabled(okEnabled && canUpdateReferences()); fRefactoring.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection()); if (fQualifiedNameCheckbox != null) { boolean enabled= okEnabled && fRefactoring.canEnableQualifiedNameUpdating(); fQualifiedNameCheckbox.setEnabled(enabled); if (enabled) { fQualifiedNameComponent.setEnabled(fRefactoring.getUpdateQualifiedNames()); if (fRefactoring.getUpdateQualifiedNames()) okButton.setEnabled(false); } else { fQualifiedNameComponent.setEnabled(false); } fRefactoring.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection()); } boolean preview= okEnabled; if (preview) preview= fRefactoring.getUpdateQualifiedNames() && fRefactoring.canEnableQualifiedNameUpdating() || fReferenceCheckbox.getSelection() && canUpdateReferences(); fPreview.setEnabled(preview); } private void addUpdateReferenceComponent(Composite result) { fReferenceCheckbox= new Button(result, SWT.CHECK); fReferenceCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$ fReferenceCheckbox.setSelection(fRefactoring.getUpdateReferences()); fReferenceCheckbox.setEnabled(canUpdateReferences()); fReferenceCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fRefactoring.setUpdateReferences(((Button)e.widget).getSelection()); updateButtons(); } }); } private boolean canUpdateReferences() { try{ return fRefactoring.canUpdateReferences(); } catch (JavaModelException e){ return false; } } private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) { if (!fRefactoring.canUpdateQualifiedNames()) return; fQualifiedNameCheckbox= new Button(parent, SWT.CHECK); int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; fQualifiedNameCheckbox.setText(RefactoringMessages.getString("RenameInputWizardPage.update_qualified_names")); //$NON-NLS-1$ fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fQualifiedNameCheckbox.setSelection(fRefactoring.getUpdateQualifiedNames()); fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, fRefactoring, getRefactoringSettings()); fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData gd= (GridData)fQualifiedNameComponent.getLayoutData(); gd.horizontalAlignment= GridData.FILL; gd.horizontalIndent= indent; fQualifiedNameComponent.setEnabled(false); fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { boolean enabled= ((Button)e.widget).getSelection(); fQualifiedNameComponent.setEnabled(enabled); fRefactoring.setUpdateQualifiedNames(enabled); updateButtons(); } }); } protected IDialogSettings getRefactoringSettings() { IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings(); if (settings == null) return null; IDialogSettings result= settings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS); if (result == null) { result= new DialogSettings(RefactoringWizardPage.REFACTORING_SETTINGS); settings.addSection(result); } return result; } } } }
31,957
Bug 31957 Refactor/move doesn't remember non-java files
When refactoring with "rename", the list of non-java files is remembered from use to use. When using "move", the previous settings are ignored, and the last "rename" settings are used. This is based on the M5 build.
resolved fixed
5138d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:07:56Z
2003-02-15T23:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtMoveAction.java
package org.eclipse.jdt.internal.ui.reorg; import java.util.Iterator; import java.util.List; 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.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.DialogSettings; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.MoveProjectAction; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.QualifiedNameComponent; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard; import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog; import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardPage; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery; import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils; public class JdtMoveAction extends ReorgDestinationAction { public static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1; private boolean fShowPreview= false; public JdtMoveAction(IWorkbenchSite site) { super(site); setText(ReorgMessages.getString("moveAction.label"));//$NON-NLS-1$ } protected void run(IStructuredSelection selection) { if (ClipboardActionUtil.hasOnlyProjects(selection)){ moveProject(selection); } else { super.run(selection); } } public static ElementTreeSelectionDialog makeDialog(Shell parent, MoveRefactoring refactoring) { StandardJavaElementContentProvider cp= new StandardJavaElementContentProvider() { public boolean hasChildren(Object element) { // prevent the + from being shown in front of packages return !(element instanceof IPackageFragment) && super.hasChildren(element); } }; MoveDestinationDialog dialog= new MoveDestinationDialog( parent, new DestinationRenderer(JavaElementLabelProvider.SHOW_SMALL_ICONS), cp, refactoring); return dialog; } /* non java-doc * see @ReorgDestinationAction#isOkToProceed */ String getActionName() { return ReorgMessages.getString("moveAction.name"); //$NON-NLS-1$ } /* non java-doc * see @ReorgDestinationAction#getDestinationDialogMessage */ String getDestinationDialogMessage() { return ReorgMessages.getString("moveAction.destination.label"); //$NON-NLS-1$ } /* non java-doc * see @ReorgDestinationAction#createRefactoring */ ReorgRefactoring createRefactoring(List elements){ IPackageFragmentRootManipulationQuery query= createUpdateClasspathQuery(getShell()); return new MoveRefactoring(elements, JavaPreferencesSettings.getCodeGenerationSettings(), query); } ElementTreeSelectionDialog createDestinationSelectionDialog(Shell parent, ILabelProvider labelProvider, StandardJavaElementContentProvider cp, ReorgRefactoring refactoring){ return new MoveDestinationDialog(parent, labelProvider, cp, (MoveRefactoring)refactoring); } /* non java-doc * see @ReorgDestinationAction#isOkToProceed */ protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{ return isOkToMoveReadOnly(refactoring); } protected void setShowPreview(boolean showPreview) { fShowPreview = showPreview; } private static boolean isOkToMoveReadOnly(ReorgRefactoring refactoring){ if (! hasReadOnlyElements(refactoring)) return true; //we need to confirm this in all cases except for the case of moving cus to a package //Then, confirmation does not make sense because jcore throws an exception anyway if (refactoring.getDestination() instanceof IPackageFragment){ List list= refactoring.getElementsToReorg(); for (Iterator iter= list.iterator(); iter.hasNext();) { Object element= iter.next(); if (! (element instanceof ICompilationUnit)) return askIfOkToMoveReadOnly(); } return true; } else { return askIfOkToMoveReadOnly(); } } private static boolean askIfOkToMoveReadOnly(){ return MessageDialog.openQuestion( JavaPlugin.getActiveWorkbenchShell(), ReorgMessages.getString("moveAction.checkMove"), //$NON-NLS-1$ ReorgMessages.getString("moveAction.error.readOnly")); //$NON-NLS-1$ } private static boolean hasReadOnlyElements(ReorgRefactoring refactoring){ for (Iterator iter= refactoring.getElementsToReorg().iterator(); iter.hasNext(); ){ if (ReorgUtils.shouldConfirmReadOnly(iter.next())) return true; } return false; } protected Object openDialog(ElementTreeSelectionDialog dialog) { Object result= super.openDialog(dialog); if (dialog instanceof MoveDestinationDialog) { fShowPreview= dialog.getReturnCode() == PREVIEW_ID; } else { fShowPreview= false; } return result; } /* non java-doc * @see ReorgDestinationAction#doReorg(ReorgRefactoring) */ void reorg(ReorgRefactoring refactoring) throws JavaModelException{ if (fShowPreview){ openWizard(getShell(), refactoring); return; } else super.reorg(refactoring); } public static void openWizard(Shell parent, ReorgRefactoring refactoring) { //XX incorrect help RefactoringWizard wizard= new RefactoringWizard(refactoring, ReorgMessages.getString("JdtMoveAction.move"), IJavaHelpContextIds.MOVE_CU_ERROR_WIZARD_PAGE); //$NON-NLS-1$ wizard.setChangeCreationCancelable(false); new RefactoringWizardDialog(parent, wizard).open(); return; } private void moveProject(IStructuredSelection selection){ MoveProjectAction action= new MoveProjectAction(JavaPlugin.getActiveWorkbenchShell()); action.selectionChanged(selection); action.run(); } //--- static inner classes private static class MoveDestinationDialog extends ElementTreeSelectionDialog { private MoveRefactoring fRefactoring; private Button fReferenceCheckbox; private Button fQualifiedNameCheckbox; private QualifiedNameComponent fQualifiedNameComponent; private Button fPreview; MoveDestinationDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, MoveRefactoring refactoring) { super(parent, labelProvider, contentProvider); fRefactoring= refactoring; setDoubleClickSelects(false); } protected void updateOKStatus() { super.updateOKStatus(); try{ Button okButton= getOkButton(); boolean okEnabled= okButton.getEnabled(); fRefactoring.setDestination(getFirstResult()); fReferenceCheckbox.setEnabled(okEnabled && canUpdateReferences()); fRefactoring.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection()); if (fQualifiedNameCheckbox != null) { boolean enabled= okEnabled && fRefactoring.canEnableQualifiedNameUpdating(); fQualifiedNameCheckbox.setEnabled(enabled); if (enabled) { fQualifiedNameComponent.setEnabled(fRefactoring.getUpdateQualifiedNames()); if (fRefactoring.getUpdateQualifiedNames()) okButton.setEnabled(false); } else { fQualifiedNameComponent.setEnabled(false); } fRefactoring.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection()); } boolean preview= okEnabled; if (preview) preview= fRefactoring.getUpdateQualifiedNames() && fRefactoring.canEnableQualifiedNameUpdating() || fReferenceCheckbox.getSelection() && fRefactoring.canUpdateReferences(); fPreview.setEnabled(preview); } catch (JavaModelException e){ ExceptionHandler.handle(e, ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$ } } protected void buttonPressed(int buttonId) { super.buttonPressed(buttonId); if (buttonId == PREVIEW_ID) { setReturnCode(PREVIEW_ID); close(); } } protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.MOVE_DESTINATION_DIALOG); } protected void createButtonsForButtonBar(Composite parent) { fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$ super.createButtonsForButtonBar(parent); } protected Control createDialogArea(Composite parent) { Composite result= (Composite)super.createDialogArea(parent); addUpdateReferenceComponent(result); addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth); return result; } private void addUpdateReferenceComponent(Composite result) { fReferenceCheckbox= new Button(result, SWT.CHECK); fReferenceCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$ fReferenceCheckbox.setSelection(fRefactoring.getUpdateReferences()); fReferenceCheckbox.setEnabled(canUpdateReferences()); fReferenceCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fRefactoring.setUpdateReferences(((Button)e.widget).getSelection()); updateOKStatus(); } }); } private boolean canUpdateReferences() { try{ return fRefactoring.canUpdateReferences(); } catch (JavaModelException e){ return false; } } private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) { if (!fRefactoring.canUpdateQualifiedNames()) return; fQualifiedNameCheckbox= new Button(parent, SWT.CHECK); int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; fQualifiedNameCheckbox.setText(RefactoringMessages.getString("RenameInputWizardPage.update_qualified_names")); //$NON-NLS-1$ fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fQualifiedNameCheckbox.setSelection(fRefactoring.getUpdateQualifiedNames()); fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, fRefactoring, getRefactoringSettings()); fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData gd= (GridData)fQualifiedNameComponent.getLayoutData(); gd.horizontalAlignment= GridData.FILL; gd.horizontalIndent= indent; fQualifiedNameComponent.setEnabled(false); fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { boolean enabled= ((Button)e.widget).getSelection(); fQualifiedNameComponent.setEnabled(enabled); fRefactoring.setUpdateQualifiedNames(enabled); updateOKStatus(); } }); } protected IDialogSettings getRefactoringSettings() { IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings(); if (settings == null) return null; IDialogSettings result= settings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS); if (result == null) { result= new DialogSettings(RefactoringWizardPage.REFACTORING_SETTINGS); settings.addSection(result); } return result; } } public static IPackageFragmentRootManipulationQuery createUpdateClasspathQuery(Shell shell){ String messagePattern= ReorgMessages.getString("JdtMoveAction.referenced") + //$NON-NLS-1$ ReorgMessages.getString("JdtMoveAction.update_classpath"); //$NON-NLS-1$ return new PackageFragmentRootManipulationQuery(shell, ReorgMessages.getString("JdtMoveAction.Move"), messagePattern); //$NON-NLS-1$ } }
31,253
Bug 31253 local rename of constructors should rename class too [code manipulation]
20030206 public class A { A(int y){} } select 'A' in the constructor name- local rename does not change class name works the other way round though - select A in class name and local rename will rename the constructor for you
resolved fixed
c5343e2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:14:54Z
2003-02-07T12:13:20Z
org.eclipse.jdt.ui/core
31,253
Bug 31253 local rename of constructors should rename class too [code manipulation]
20030206 public class A { A(int y){} } select 'A' in the constructor name- local rename does not change class name works the other way round though - select A in class name and local rename will rename the constructor for you
resolved fixed
c5343e2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:14:54Z
2003-02-07T12:13:20Z
extension/org/eclipse/jdt/internal/corext/dom/Bindings.java
31,253
Bug 31253 local rename of constructors should rename class too [code manipulation]
20030206 public class A { A(int y){} } select 'A' in the constructor name- local rename does not change class name works the other way round though - select A in class name and local rename will rename the constructor for you
resolved fixed
c5343e2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-18T19:14:54Z
2003-02-07T12:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LinkedNamesAssistProposal.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; /** * A template proposal. */ public class LinkedNamesAssistProposal implements IJavaCompletionProposal, ICompletionProposalExtension2 { private SimpleName fNode; private IRegion fSelectedRegion; // initialized by apply() private static class LinkedNodeFinder extends ASTVisitor { private IBinding fBinding; private ArrayList fResult; public LinkedNodeFinder(IBinding binding, ArrayList result) { fBinding= binding; fResult= result; } public boolean visit(MethodDeclaration node) { if (node.isConstructor() && fBinding.getKind() == IBinding.TYPE) { ASTNode typeNode= node.getParent(); if (typeNode instanceof TypeDeclaration) { if (fBinding == ((TypeDeclaration) typeNode).resolveBinding()) { fResult.add(node.getName()); } } } return true; } public boolean visit(SimpleName node) { if (fBinding == node.resolveBinding()) { fResult.add(node); } return false; } } public LinkedNamesAssistProposal(SimpleName node) { fNode= node; } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { try { ArrayList sameNodes= new ArrayList(); LinkedNodeFinder finder= new LinkedNodeFinder(fNode.resolveBinding(), sameNodes); ASTResolving.findParentCompilationUnit(fNode).accept(finder); IDocument document= viewer.getDocument(); LinkedPositionManager manager= new LinkedPositionManager(document); for (int i= 0; i < sameNodes.size(); i++) { ASTNode elem= (ASTNode) sameNodes.get(i); manager.addPosition(elem.getStartPosition(), elem.getLength()); } LinkedPositionUI editor= new LinkedPositionUI(viewer, manager); editor.setInitialOffset(offset); editor.setFinalCaretOffset(offset); editor.enter(); fSelectedRegion= editor.getSelectedRegion(); } catch (BadLocationException e) { } } /* * @see ICompletionProposal#apply(IDocument) */ public void apply(IDocument document) { // can't do anything } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { return CorrectionMessages.getString("LinkedNamesAssistProposal.proposalinfo"); //$NON-NLS-1$ } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { return CorrectionMessages.getString("LinkedNamesAssistProposal.description"); //$NON-NLS-1$ } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return null; } /* * @see IJavaCompletionProposal#getRelevance() */ public int getRelevance() { return 1; } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean) */ public void selected(ITextViewer textViewer, boolean smartToggle) { } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer) */ public void unselected(ITextViewer textViewer) { } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent) */ public boolean validate(IDocument document, int offset, DocumentEvent event) { return false; } }
31,769
Bug 31769 progress monitor indication incorrect after resizing [JUnit]
20030211 i'm running a test class with 95 tests i have junit as a fast view in the middle of it running, i resized the view a bit, which made the progress bar jump immediately to 100% and stay there (the numbers were still ticking correctly) don't know if it's junit or swt
resolved fixed
3fd2a6f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T00:21:32Z
2003-02-13T15:26:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitProgressBar.java
package org.eclipse.jdt.internal.junit.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; /** * A progress bar with a red/green indication for success or failure. */ public class JUnitProgressBar extends Canvas { private static final int DEFAULT_WIDTH = 160; private static final int DEFAULT_HEIGHT = 18; private int fSelection= 0; private int fMax= 0; private int fX= 0; private boolean fError; public JUnitProgressBar(Composite parent) { super(parent, SWT.NONE); addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { fX= scale(fX); redraw(); } }); addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { paint(e); } }); addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e){ } }); } public void setMaximum(int max) { fMax= max; } public void reset() { fError= false; fSelection= 0; fX= 0; fMax= 0; redraw(); } private void paintStep(int startX, int endX) { GC gc = new GC(this); setStatusColor(gc); Rectangle rect= getClientArea(); startX= Math.max(1, startX); gc.fillRectangle(startX, 1, endX-startX, rect.height-2); gc.dispose(); } private void setStatusColor(GC gc) { if (fError) gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_RED)); else gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_GREEN)); } private int scale(int value) { if (fMax > 0) { Rectangle r= getClientArea(); if (r.width != 0) return Math.max(0, value*(r.width-2)/fMax); } return value; } private void drawBevelRect(GC gc, int x, int y, int w, int h, Color topleft, Color bottomright) { gc.setForeground(topleft); gc.drawLine(x, y, x+w-1, y); gc.drawLine(x, y, x, y+h-1); gc.setForeground(bottomright); gc.drawLine(x+w, y, x+w, y+h); gc.drawLine(x, y+h, x+w, y+h); } private void paint(PaintEvent event) { GC gc = event.gc; Display disp= getDisplay(); Rectangle rect= getClientArea(); gc.fillRectangle(rect); drawBevelRect(gc, rect.x, rect.y, rect.width-1, rect.height-1, disp.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW), disp.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); setStatusColor(gc); fX= Math.min(rect.width-2, fX); gc.fillRectangle(1, 1, fX, rect.height-2); } public Point computeSize(int wHint, int hHint, boolean changed) { checkWidget(); Point size= null; size= new Point(DEFAULT_WIDTH, DEFAULT_HEIGHT); if (wHint != SWT.DEFAULT) size.x= wHint; if (hHint != SWT.DEFAULT) size.y= hHint; return size; } public void step(int failures) { fSelection++; int x= fX; fX= scale(fSelection); if (!fError && failures > 0) { fError= true; x= 1; } if (fSelection == fMax) fX= getClientArea().width-1; paintStep(x, fX); } }
31,280
Bug 31280 'Format' should be under 'Source'
20030206 'format' should be a submenu entry for 'source' it looks very strange now that we have the 'sort members' action (people who use it often probebly use the shortcut anyway)
resolved fixed
f025442
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T09:05:15Z
2003-02-07T15:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITextViewerExtension3; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.editors.text.IStorageDocumentProvider; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.TextOperationAction; 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.ISourceRange; import org.eclipse.jdt.core.ISourceReference; 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.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant; import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant; import org.eclipse.jdt.internal.ui.text.java.SmartBracesAutoEditStrategy; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.RefactorActionGroup; /** * Java specific text editor. */ public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant { /** * Text operation code for requesting correction assist to show correction * proposals for the current position. */ public static final int CORRECTIONASSIST_PROPOSALS= 50; interface ITextConverter { void customizeDocumentCommand(IDocument document, DocumentCommand command); }; class AdaptedSourceViewer extends JavaSourceViewer { private List fTextConverters; private boolean fIgnoreTextConverters= false; private JavaCorrectionAssistant fCorrectionAssistant; public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) { super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles); } public IContentAssistant getContentAssistant() { return fContentAssistant; } /* * @see ITextOperationTarget#doOperation(int) */ public void doOperation(int operation) { if (getTextWidget() == null) return; switch (operation) { case CONTENTASSIST_PROPOSALS: String msg= fContentAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case CORRECTIONASSIST_PROPOSALS: fCorrectionAssistant.showPossibleCompletions(); return; case UNDO: fIgnoreTextConverters= true; break; case REDO: fIgnoreTextConverters= true; break; } super.doOperation(operation); } /* * @see ITextOperationTarget#canDoOperation(int) */ public boolean canDoOperation(int operation) { if (operation == CORRECTIONASSIST_PROPOSALS) return true; return super.canDoOperation(operation); } /* * @see TextViewer#handleDispose() */ protected void handleDispose() { if (fCorrectionAssistant != null) { fCorrectionAssistant.uninstall(); fCorrectionAssistant= null; } super.handleDispose(); } public void insertTextConverter(ITextConverter textConverter, int index) { throw new UnsupportedOperationException(); } public void addTextConverter(ITextConverter textConverter) { if (fTextConverters == null) { fTextConverters= new ArrayList(1); fTextConverters.add(textConverter); } else if (!fTextConverters.contains(textConverter)) fTextConverters.add(textConverter); } public void removeTextConverter(ITextConverter textConverter) { if (fTextConverters != null) { fTextConverters.remove(textConverter); if (fTextConverters.size() == 0) fTextConverters= null; } } /* * @see TextViewer#customizeDocumentCommand(DocumentCommand) */ protected void customizeDocumentCommand(DocumentCommand command) { super.customizeDocumentCommand(command); if (!fIgnoreTextConverters && fTextConverters != null) { for (Iterator e = fTextConverters.iterator(); e.hasNext();) ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command); } fIgnoreTextConverters= false; } // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 public void updateIndentationPrefixes() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(this); for (int i= 0; i < types.length; i++) { String[] prefixes= configuration.getIndentPrefixes(this, types[i]); if (prefixes != null && prefixes.length > 0) setIndentPrefixes(prefixes, types[i]); } } /* * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) */ public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester); } /* * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) */ public void configure(SourceViewerConfiguration configuration) { super.configure(configuration); fCorrectionAssistant= new JavaCorrectionAssistant(CompilationUnitEditor.this); fCorrectionAssistant.install(this); prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this), IDocument.DEFAULT_CONTENT_TYPE); } }; static class TabConverter implements ITextConverter { private int fTabRatio; private ILineTracker fLineTracker; public TabConverter() { } public void setNumberOfSpacesPerTab(int ratio) { fTabRatio= ratio; } public void setLineTracker(ILineTracker lineTracker) { fLineTracker= lineTracker; } private int insertTabString(StringBuffer buffer, int offsetInLine) { if (fTabRatio == 0) return 0; int remainder= offsetInLine % fTabRatio; remainder= fTabRatio - remainder; for (int i= 0; i < remainder; i++) buffer.append(' '); return remainder; } public void customizeDocumentCommand(IDocument document, DocumentCommand command) { String text= command.text; if (text == null) return; int index= text.indexOf('\t'); if (index > -1) { StringBuffer buffer= new StringBuffer(); fLineTracker.set(command.text); int lines= fLineTracker.getNumberOfLines(); try { for (int i= 0; i < lines; i++) { int offset= fLineTracker.getLineOffset(i); int endOffset= offset + fLineTracker.getLineLength(i); String line= text.substring(offset, endOffset); int position= 0; if (i == 0) { IRegion firstLine= document.getLineInformationOfOffset(command.offset); position= command.offset - firstLine.getOffset(); } int length= line.length(); for (int j= 0; j < length; j++) { char c= line.charAt(j); if (c == '\t') { position += insertTabString(buffer, position); } else { buffer.append(c); ++ position; } } } command.text= buffer.toString(); } catch (BadLocationException x) { } } } }; private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { final char fExitCharacter; final Stack fStack; final int fSize; public ExitPolicy(char exitCharacter, Stack stack) { fExitCharacter= exitCharacter; fStack= stack; fSize= fStack.size(); } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (fSize == fStack.size()) { if (manager.anyPositionIncludes(offset, length)) return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false); else return new ExitFlags(LinkedPositionUI.COMMIT, true); } } switch (event.character) { case '\b': if (manager.getFirstPosition().length == 0) return new ExitFlags(0, false); else return null; case '\n': case '\r': return new ExitFlags(LinkedPositionUI.COMMIT, true); default: return null; } } }; private static class BracketLevel { int fOffset; int fLength; LinkedPositionManager fManager; LinkedPositionUI fEditor; }; private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener { private boolean fCloseBrackets= true; private boolean fCloseStrings= true; private Stack fBracketLevelStack= new Stack(); public void setCloseBracketsEnabled(boolean enabled) { fCloseBrackets= enabled; } public void setCloseStringsEnabled(boolean enabled) { fCloseStrings= enabled; } private boolean hasIdentifierToTheRight(IDocument document, int offset) { try { int end= offset; IRegion endLine= document.getLineInformationOfOffset(end); int maxEnd= endLine.getOffset() + endLine.getLength(); while (end != maxEnd && Character.isWhitespace(document.getChar(end))) ++end; return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end)); } catch (BadLocationException e) { // be conservative return true; } } private boolean hasIdentifierToTheLeft(IDocument document, int offset) { try { int start= offset; IRegion startLine= document.getLineInformationOfOffset(start); int minStart= startLine.getOffset(); while (start != minStart && Character.isWhitespace(document.getChar(start - 1))) --start; return start != minStart && Character.isJavaIdentifierPart(document.getChar(start - 1)); } catch (BadLocationException e) { return true; } } private boolean hasCharacterToTheRight(IDocument document, int offset, char character) { try { int end= offset; IRegion endLine= document.getLineInformationOfOffset(end); int maxEnd= endLine.getOffset() + endLine.getLength(); while (end != maxEnd && Character.isWhitespace(document.getChar(end))) ++end; return end != maxEnd && document.getChar(end) == character; } catch (BadLocationException e) { // be conservative return true; } } /* * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ public void verifyKey(VerifyEvent event) { if (!event.doit) return; final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); final Point selection= sourceViewer.getSelectedRange(); final int offset= selection.x; final int length= selection.y; switch (event.character) { case '(': if (hasCharacterToTheRight(document, offset + length, '(')) return; // fall through case '[': if (!fCloseBrackets) return; if (hasIdentifierToTheRight(document, offset + length)) return; // fall through case '"': if (event.character == '"') { if (!fCloseStrings) return; if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } try { ITypedRegion partition= document.getPartition(offset); if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset) return; if (!validateEditorInputState()) return; final char character= event.character; final char closingCharacter= getPeerCharacter(character); final StringBuffer buffer= new StringBuffer(); buffer.append(character); buffer.append(closingCharacter); document.replace(offset, length, buffer.toString()); BracketLevel level= new BracketLevel(); fBracketLevelStack.push(level); level.fManager= new LinkedPositionManager(document, fBracketLevelStack.size() > 1); level.fManager.addPosition(offset + 1, 0); level.fOffset= offset; level.fLength= 2; level.fEditor= new LinkedPositionUI(sourceViewer, level.fManager); level.fEditor.setCancelListener(this); level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, fBracketLevelStack)); level.fEditor.setFinalCaretOffset(offset + 2); level.fEditor.enter(); IRegion newSelection= level.fEditor.getSelectedRegion(); sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength()); event.doit= false; } catch (BadLocationException e) { } break; } } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean) */ public void exit(boolean accept) { BracketLevel level= (BracketLevel) fBracketLevelStack.pop(); if (accept) return; // remove brackets try { final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); document.replace(level.fOffset, level.fLength, null); } catch (BadLocationException e) { } } }; /** Preference key for code formatter tab size */ private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; /** Preference key for inserting spaces rather than tabs */ private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS; /** Preference key for automatically closing strings */ private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS; /** Preference key for automatically closing brackets and parenthesis */ private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS; /** The editor's save policy */ protected ISavePolicy fSavePolicy; /** Listener to annotation model changes that updates the error tick in the tab image */ private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater; /** The editor's tab converter */ private TabConverter fTabConverter; /** The remembered java element */ private IJavaElement fRememberedElement; /** The remembered selection */ private ITextSelection fRememberedSelection; /** The remembered java element offset */ private int fRememberedElementOffset; /** The bracket inserter. */ private BracketInserter fBracketInserter= new BracketInserter(); /** The standard action groups added to the menu */ private GenerateActionGroup fGenerateActionGroup; private CompositeActionGroup fContextMenuGroup; /** * Creates a new compilation unit editor. */ public CompilationUnitEditor() { super(); setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider()); setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$ setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$ // don't set help contextId, we install our own help context fSavePolicy= null; fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this); } /* * @see AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$ action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction("ContentAssistProposal", action); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT); setAction("Comment", action); //$NON-NLS-1$ markAsStateDependentAction("Comment", true); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT); setAction("Uncomment", action); //$NON-NLS-1$ markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT); setAction("Format", action); //$NON-NLS-1$ markAsStateDependentAction("Format", true); //$NON-NLS-1$ markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); fActionGroups.addGroup(rg); fActionGroups.addGroup(fGenerateActionGroup); // We have to keep the context menu group separate to have better control over positioning fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup, rg, new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)}); } /* * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementAt(int offset) { return getElementAt(offset, true); } /** * Returns the most narrow element including the given offset. If <code>reconcile</code> * is <code>true</code> the editor's input element is reconciled in advance. If it is * <code>false</code> this method only returns a result if the editor's input element * does not need to be reconciled. * * @param offset the offset included by the retrieved element * @param reconcile <code>true</code> if working copy should be reconciled */ protected IJavaElement getElementAt(int offset, boolean reconcile) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { if (reconcile) { synchronized (unit) { unit.reconcile(); } return unit.getElementAt(offset); } else if (unit.isConsistent()) return unit.getElementAt(offset); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /* * @see JavaEditor#getCorrespondingElement(IJavaElement) */ protected IJavaElement getCorrespondingElement(IJavaElement element) { try { return EditorUtility.getWorkingCopy(element, true); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } return null; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$ ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /* * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) */ protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { if (page != null) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); page.setInput(manager.getWorkingCopy(input)); } } /* * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor) */ protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p; cp.setSavePolicy(fSavePolicy); } try { super.performSaveOperation(operation, progressMonitor); } finally { if (p instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p; cp.setSavePolicy(null); } } } /* * @see AbstractTextEditor#doSaveAs */ public void doSaveAs() { if (askIfNonWorkbenchEncodingIsOk()) { super.doSaveAs(); } } /* * @see AbstractTextEditor#doSave(IProgressMonitor) */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) { // editor has been closed return; } if (!askIfNonWorkbenchEncodingIsOk()) { progressMonitor.setCanceled(true); return; } if (p.isDeleted(getEditorInput())) { if (isSaveAsAllowed()) { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(progressMonitor); } else { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Missing resources. */ Shell shell= getSite().getShell(); MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { setStatusLineErrorMessage(null); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { performSaveOperation(createSaveOperation(false), progressMonitor); } } else performSaveOperation(createSaveOperation(false), progressMonitor); } } /** * Asks the user if it is ok to store in non-workbench encoding. * @return <true> if the user wants to continue */ private boolean askIfNonWorkbenchEncodingIsOk() { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IStorageDocumentProvider) { IEditorInput input= getEditorInput(); IStorageDocumentProvider storageProvider= (IStorageDocumentProvider)provider; String encoding= storageProvider.getEncoding(input); String defaultEncoding= storageProvider.getDefaultEncoding(); if (encoding != null && !encoding.equals(defaultEncoding)) { Shell shell= getSite().getShell(); String title= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ String msg; if (input != null) msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$ else msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$ return MessageDialog.openQuestion(shell, title, msg); } } return true; } public boolean isSaveAsAllowed() { return true; } /** * The compilation unit editor implementation of this <code>AbstractTextEditor</code> * method asks the user for the workspace path of a file resource and saves the document * there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); IEditorInput input = getEditorInput(); SaveAsDialog dialog= new SaveAsDialog(shell); IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; if (original != null) dialog.setOriginalFile(original); dialog.create(); IDocumentProvider provider= getDocumentProvider(); if (provider == null) { // editor has been programmatically closed while the dialog was open return; } if (provider.isDeleted(input) && original != null) { String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ dialog.setErrorMessage(null); dialog.setMessage(message, IMessageProvider.WARNING); } if (dialog.open() == Dialog.CANCEL) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IPath filePath= dialog.getResult(); if (filePath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IWorkspace workspace= ResourcesPlugin.getWorkspace(); IFile file= workspace.getRoot().getFile(filePath); final IEditorInput newInput= new FileEditorInput(file); WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(final IProgressMonitor monitor) throws CoreException { getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); } }; boolean success= false; try { provider.aboutToChange(newInput); new ProgressMonitorDialog(shell).run(false, true, op); success= true; } catch (InterruptedException x) { } catch (InvocationTargetException x) { Throwable t= x.getTargetException(); if (t instanceof CoreException) { CoreException cx= (CoreException) t; ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ } else { MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { provider.changed(newInput); if (success) setInput(newInput); } if (progressMonitor != null) progressMonitor.setCanceled(!success); } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); configureTabConverter(); } private void configureTabConverter() { if (fTabConverter != null) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cup= (CompilationUnitDocumentProvider) provider; fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); } } } private int getTabSize() { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); return preferences.getInt(CODE_FORMATTER_TAB_SIZE); } private void startTabConversion() { if (fTabConverter == null) { fTabConverter= new TabConverter(); configureTabConverter(); fTabConverter.setNumberOfSpacesPerTab(getTabSize()); AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.addTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); } } private void stopTabConversion() { if (fTabConverter != null) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.removeTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); fTabConverter= null; } } private boolean isTabConversionEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(SPACES_FOR_TABS); } public void dispose() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter); if (fJavaEditorErrorTickUpdater != null) { fJavaEditorErrorTickUpdater.dispose(); fJavaEditorErrorTickUpdater= null; } if (fActionGroups != null) { fActionGroups.dispose(); fActionGroups= null; } super.dispose(); } /* * @see AbstractTextEditor#createPartControl(Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); if (isTabConversionEnabled()) startTabConversion(); IPreferenceStore preferenceStore= getPreferenceStore(); boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS); boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS); fBracketInserter.setCloseBracketsEnabled(closeBrackets); fBracketInserter.setCloseStringsEnabled(closeStrings); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter); } private static char getPeerCharacter(char character) { switch (character) { case '(': return ')'; case ')': return '('; case '[': return ']'; case ']': return '['; case '"': return character; default: throw new IllegalArgumentException(); } } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CLOSE_BRACKETS.equals(p)) { fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p)); return; } if (CLOSE_STRINGS.equals(p)) { fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p)); return; } if (SPACES_FOR_TABS.equals(p)) { if (isTabConversionEnabled()) startTabConversion(); else stopTabConversion(); return; } IContentAssistant c= asv.getContentAssistant(); if (c instanceof ContentAssistant) ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event); } } finally { super.handlePreferenceStoreChanged(event); } } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent) */ protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CODE_FORMATTER_TAB_SIZE.equals(p)) { asv.updateIndentationPrefixes(); if (fTabConverter != null) fTabConverter.setNumberOfSpacesPerTab(getTabSize()); } } super.handlePreferencePropertyChanged(event); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) { return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles); } public void synchronizeOutlinePageSelection() { if (isEditingScriptRunning()) return; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null || fOutlinePage == null) return; StyledText styledText= sourceViewer.getTextWidget(); if (styledText == null) return; int modelCaret= 0; if (sourceViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer; modelCaret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); } else { int offset= sourceViewer.getVisibleRegion().getOffset(); modelCaret= offset + styledText.getCaretOffset(); } IJavaElement element= getElementAt(modelCaret, false); ISourceReference reference= getSourceReference(element, modelCaret); if (reference != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select(reference); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } } private ISourceReference getSourceReference(IJavaElement element, int offset) { if ( !(element instanceof ISourceReference)) return null; if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { IImportDeclaration declaration= (IImportDeclaration) element; IImportContainer container= (IImportContainer) declaration.getParent(); ISourceRange srcRange= null; try { srcRange= container.getSourceRange(); } catch (JavaModelException e) { } if (srcRange != null && srcRange.getOffset() == offset) return container; } return (ISourceReference) element; } /* * @see IReconcilingParticipant#reconciled() */ public void reconciled() { if (synchronizeOutlineOnCursorMove()) { Shell shell= getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(new Runnable() { public void run() { synchronizeOutlinePageSelection(); } }); } } } private boolean synchronizeOutlineOnCursorMove() { return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE); } protected void updateStateDependentActions() { super.updateStateDependentActions(); fGenerateActionGroup.editorStateChanged(); } /** * Returns the updated java element for the old java element. */ private IJavaElement findElement(IJavaElement element) { if (element == null) return null; IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { synchronized (unit) { unit.reconcile(); } IJavaElement[] findings= unit.findElements(element); if (findings != null && findings.length > 0) return findings[0]; } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /** * Returns the offset of the given Java element. */ private int getOffset(IJavaElement element) { if (element instanceof ISourceReference) { ISourceReference sr= (ISourceReference) element; try { ISourceRange srcRange= sr.getSourceRange(); if (srcRange != null) return srcRange.getOffset(); } catch (JavaModelException e) { } } return -1; } /* * @see AbstractTextEditor#rememberSelection() */ protected void rememberSelection() { ISelectionProvider sp= getSelectionProvider(); fRememberedSelection= (sp == null ? null : (ITextSelection) sp.getSelection()); if (fRememberedSelection != null) { fRememberedElement= getElementAt(fRememberedSelection.getOffset(), true); fRememberedElementOffset= getOffset(fRememberedElement); } } /* * @see AbstractTextEditor#restoreSelection() */ protected void restoreSelection() { try { if (getSourceViewer() == null || fRememberedSelection == null) return; IJavaElement newElement= findElement(fRememberedElement); int newOffset= getOffset(newElement); int delta= (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - fRememberedElementOffset : 0; if (isValidSelection(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength())) selectAndReveal(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength()); } finally { fRememberedSelection= null; fRememberedElement= null; fRememberedElementOffset= -1; } } private boolean isValidSelection(int offset, int length) { IDocumentProvider provider= getDocumentProvider(); if (provider != null) { IDocument document= provider.getDocument(getEditorInput()); if (document != null) { int end= offset + length; int documentLength= document.getLength(); return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength; } } return false; } /* * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) */ protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { String oldExtension= ""; //$NON-NLS-1$ if (originalElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) originalElement).getFile(); if (file != null) { String ext= file.getFileExtension(); if (ext != null) oldExtension= ext; } } String newExtension= ""; //$NON-NLS-1$ if (movedElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) movedElement).getFile(); if (file != null) newExtension= file.getFileExtension(); } return oldExtension.equals(newExtension); } }
31,280
Bug 31280 'Format' should be under 'Source'
20030206 'format' should be a submenu entry for 'source' it looks very strange now that we have the 'sort members' action (people who use it often probebly use the shortcut anyway)
resolved fixed
f025442
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T09:05:15Z
2003-02-07T15:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateActionGroup.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.ui.actions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.AddBookmarkAction; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.ConvertLineDelimitersAction; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.AddTaskAction; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.ui.IContextMenuConstants; /** * Action group that adds the source and generate actions to a part's context * menu and installs handlers for the corresponding global menu actions. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class GenerateActionGroup extends ActionGroup { private CompilationUnitEditor fEditor; private IWorkbenchSite fSite; private String fGroupName= IContextMenuConstants.GROUP_SOURCE; private List fRegisteredSelectionListeners; private AddImportOnSelectionAction fAddImport; private OverrideMethodsAction fOverrideMethods; private AddGetterSetterAction fAddGetterSetter; private AddDelegateMethodsAction fAddDelegateMethods; private AddUnimplementedConstructorsAction fAddUnimplementedConstructors; private AddJavaDocStubAction fAddJavaDocStub; private AddBookmarkAction fAddBookmark; private AddTaskAction fAddTaskAction; private ExternalizeStringsAction fExternalizeStrings; private FindStringsToExternalizeAction fFindStringsToExternalize; private SurroundWithTryCatchAction fSurroundWithTryCatch; private AddToClasspathAction fAddToClasspathAction; private RemoveFromClasspathAction fRemoveFromClasspathAction; private OrganizeImportsAction fOrganizeImports; private SortMembersAction fSortMembers; private ConvertLineDelimitersAction fConvertToWindows; private ConvertLineDelimitersAction fConvertToUNIX; private ConvertLineDelimitersAction fConvertToMac; /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public GenerateActionGroup(CompilationUnitEditor editor, String groupName) { fSite= editor.getSite(); fEditor= editor; fGroupName= groupName; ICompilationUnit input= SelectionConverter.getInputAsCompilationUnit(editor); if (input == null || !JavaModelUtil.isOnClasspath(input)) return; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fAddImport= new AddImportOnSelectionAction(editor); fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT); fAddImport.update(); editor.setAction("AddImport", fAddImport); //$NON-NLS-1$ fOrganizeImports= new OrganizeImportsAction(editor); fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS); editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$ fSortMembers= new SortMembersAction(editor); fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS); editor.setAction("SortMembers", fSortMembers); //$NON-NLS-1$ fOverrideMethods= new OverrideMethodsAction(editor); fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS); editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$ fAddGetterSetter= new AddGetterSetterAction(editor); fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER); editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$ fAddDelegateMethods= new AddDelegateMethodsAction(editor); fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS); editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$ fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor); fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS); editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$ fAddJavaDocStub= new AddJavaDocStubAction(editor); fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor); fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH); fSurroundWithTryCatch.update(selection); provider.addSelectionChangedListener(fSurroundWithTryCatch); editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); //$NON-NLS-1$ fExternalizeStrings= new ExternalizeStringsAction(editor); fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS); editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$ fConvertToWindows= new ConvertLineDelimitersAction(editor, "\r\n"); //$NON-NLS-1$ fConvertToWindows.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS); editor.setAction("ConvertLineDelimitersToWindows", fConvertToWindows); //$NON-NLS-1$ fConvertToUNIX= new ConvertLineDelimitersAction(editor, "\n"); //$NON-NLS-1$ fConvertToUNIX.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_UNIX); editor.setAction("ConvertLineDelimitersToUNIX", fConvertToUNIX); //$NON-NLS-1$ fConvertToMac= new ConvertLineDelimitersAction(editor, "\r"); //$NON-NLS-1$ fConvertToMac.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_MAC); editor.setAction("ConvertLineDelimitersToMac", fConvertToMac); //$NON-NLS-1$ } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the page's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param page the page that owns this action group */ public GenerateActionGroup(Page page) { this(page.getSite()); } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the part's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public GenerateActionGroup(IViewPart part) { this(part.getSite()); } private GenerateActionGroup(IWorkbenchSite site) { fSite= site; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fOverrideMethods= new OverrideMethodsAction(site); fAddGetterSetter= new AddGetterSetterAction(site); fAddDelegateMethods= new AddDelegateMethodsAction(site); fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site); fAddJavaDocStub= new AddJavaDocStubAction(site); fAddBookmark= new AddBookmarkAction(site.getShell()); fAddToClasspathAction= new AddToClasspathAction(site); fRemoveFromClasspathAction= new RemoveFromClasspathAction(site); fAddTaskAction= new AddTaskAction(site); fExternalizeStrings= new ExternalizeStringsAction(site); fFindStringsToExternalize= new FindStringsToExternalizeAction(site); fOrganizeImports= new OrganizeImportsAction(site); fSortMembers= new SortMembersAction(site); fOverrideMethods.update(selection); fAddGetterSetter.update(selection); fAddDelegateMethods.update(selection); fAddUnimplementedConstructors.update(selection); fAddJavaDocStub.update(selection); fExternalizeStrings.update(selection); fFindStringsToExternalize.update(selection); fAddTaskAction.update(selection); fOrganizeImports.update(selection); fSortMembers.update(selection); if (selection instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection)selection; fAddBookmark.selectionChanged(ss); } else { fAddBookmark.setEnabled(false); } registerSelectionListener(provider, fOverrideMethods); registerSelectionListener(provider, fAddGetterSetter); registerSelectionListener(provider, fAddDelegateMethods); registerSelectionListener(provider, fAddUnimplementedConstructors); registerSelectionListener(provider, fAddJavaDocStub); registerSelectionListener(provider, fAddBookmark); registerSelectionListener(provider, fAddToClasspathAction); registerSelectionListener(provider, fRemoveFromClasspathAction); registerSelectionListener(provider, fExternalizeStrings); registerSelectionListener(provider, fFindStringsToExternalize); registerSelectionListener(provider, fOrganizeImports); registerSelectionListener(provider, fSortMembers); registerSelectionListener(provider, fAddTaskAction); } private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) { if (fRegisteredSelectionListeners == null) fRegisteredSelectionListeners= new ArrayList(20); provider.addSelectionChangedListener(listener); fRegisteredSelectionListeners.add(listener); } /* * The state of the editor owning this action group has changed. * This method does nothing if the group's owner isn't an * editor. */ /** * Note: This method is for internal use only. Clients should not call this method. */ public void editorStateChanged() { Assert.isTrue(isEditorOwner()); // http://dev.eclipse.org/bugs/show_bug.cgi?id=17709 fConvertToMac.update(); fConvertToUNIX.update(); fConvertToWindows.update(); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillActionBars(IActionBars actionBar) { super.fillActionBars(actionBar); setGlobalActionHandlers(actionBar); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); if (isEditorOwner()) { IMenuManager subMenu= createEditorSubMenu(menu); if (subMenu != null) menu.appendToGroup(fGroupName, subMenu); } else { appendToGroup(menu, fOrganizeImports); appendToGroup(menu, fOverrideMethods); appendToGroup(menu, fAddGetterSetter); appendToGroup(menu, fAddDelegateMethods); appendToGroup(menu, fAddUnimplementedConstructors); appendToGroup(menu, fAddJavaDocStub); appendToGroup(menu, fAddToClasspathAction); appendToGroup(menu, fRemoveFromClasspathAction); } } private IMenuManager createEditorSubMenu(IMenuManager mainMenu) { IMenuManager result= new MenuManager(ActionMessages.getString("SourceMenu.label")); //$NON-NLS-1$ int added= 0; added+= addEditorAction(result, "Comment"); //$NON-NLS-1$ added+= addEditorAction(result, "Uncomment"); //$NON-NLS-1$ result.add(new Separator()); added+= addAction(result, fOrganizeImports); added+= addAction(result, fAddImport); result.add(new Separator()); added+= addAction(result, fOverrideMethods); added+= addAction(result, fAddGetterSetter); added+= addAction(result, fAddDelegateMethods); added+= addAction(result, fAddUnimplementedConstructors); added+= addAction(result, fAddJavaDocStub); added+= addAction(result, fSortMembers); added+= addAction(result, fAddBookmark); result.add(new Separator()); added+= addAction(result, fSurroundWithTryCatch); added+= addAction(result, fExternalizeStrings); if (added == 0) result= null; return result; } /* (non-Javadoc) * Method declared in ActionGroup */ public void dispose() { if (fRegisteredSelectionListeners != null) { ISelectionProvider provider= fSite.getSelectionProvider(); for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) { ISelectionChangedListener listener= (ISelectionChangedListener) iter.next(); provider.removeSelectionChangedListener(listener); } } fEditor= null; super.dispose(); } private void setGlobalActionHandlers(IActionBars actionBar) { actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport); actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatch); actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub); actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings); actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize); actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports); actionBar.setGlobalActionHandler(JdtActionConstants.SORT_MEMBERS, fSortMembers); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_WINDOWS, fConvertToWindows); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_UNIX, fConvertToUNIX); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_MAC, fConvertToMac); if (!isEditorOwner()) { // editor provides its own implementation of these actions. actionBar.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmark); actionBar.setGlobalActionHandler(IWorkbenchActionConstants.ADD_TASK, fAddTaskAction); } } private int appendToGroup(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.appendToGroup(fGroupName, action); return 1; } return 0; } private int addAction(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.add(action); return 1; } return 0; } private int addEditorAction(IMenuManager menu, String actionID) { if (fEditor == null) return 0; IAction action= fEditor.getAction(actionID); if (action == null) return 0; if (action instanceof IUpdate) ((IUpdate)action).update(); if (action.isEnabled()) { menu.add(action); return 1; } return 0; } private boolean isEditorOwner() { return fEditor != null; } }
15,277
Bug 15277 Recreate test suite allows you to add the suite to itself
If you have a test suite that is also a test case (done to allow cascading tests), and recreate the test suite, you're allowed to add the suite to itself. This results in a recursive call to .suite(), which ends up causing a stack overflow when run. I'm not too sure on this, but I believe previously in this situtation the suite was added to itself a test case (new Suite(class) as opposed to class.suite()), which prevented this from happening. I do prefer this new behaviour, as it makes chaining suites together much easier (now if it only searched sub-packages for suites). This one special case just needs to be handled better.
resolved fixed
8362d19
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T14:15:02Z
2002-05-05T03:40:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestSuiteCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.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.junit.ui.IJUnitHelpContextIds; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.ExceptionHandler; 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.SWTUtil; 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.IDialogSettings; 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; import org.eclipse.ui.help.WorkbenchHelp; /** * 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$ 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$ public static final String START_MARKER= "//$JUnit-BEGIN$"; //$NON-NLS-1$ public static final String END_MARKER= "//$JUnit-END$"; //$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 MethodStubsSelectionButtonGroup fMethodStubsButtons; private boolean fUpdatedExistingClassButton; protected IStatus fClassesInSuiteStatus; protected IStatus fSuiteNameStatus; public NewTestSuiteCreationWizardPage() { super(true, PAGE_NAME); fSuiteNameStatus= new JUnitStatus(); fSuiteNameTextInitialValue= ""; //$NON-NLS-1$ setTitle(WizardMessages.getString("NewTestSuiteWizPage.title")); //$NON-NLS-1$ setDescription(WizardMessages.getString("NewTestSuiteWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ }; fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage2.method.Stub.label")); //$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); createMethodStubSelectionControls(composite, nColumns); setControl(composite); restoreWidgetValues(); WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTSUITE_WIZARD_PAGE); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } /** * Should be called from the wizard with the initial selection. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); doStatusUpdate(); fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text } /** * @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); } /** * @see DialogPage#setVisible(boolean) */ 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(WizardMessages.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= 80; 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(WizardMessages.getString("NewTestSuiteWizPage.selectAll")); //$NON-NLS-1$ GridData bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); bgd.heightHint = SWTUtil.getButtonHeigthHint(fSelectAllButton); bgd.widthHint = SWTUtil.getButtonWidthHint(fSelectAllButton); 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(WizardMessages.getString("NewTestSuiteWizPage.deselectAll")); //$NON-NLS-1$ bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); bgd.heightHint = SWTUtil.getButtonHeigthHint(fDeselectAllButton); bgd.widthHint = SWTUtil.getButtonWidthHint(fDeselectAllButton); 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 { public ClassesInSuitContentProvider() { super(); } public Object[] getElements(Object parent) { try { if (parent instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) parent; if (pack.exists()) { 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, ImportsManager imports, IProgressMonitor monitor) throws CoreException { writeImports(imports); if (fMethodStubsButtons.isEnabled() && fMethodStubsButtons.isSelected(0)) createMain(type); type.createMethod(getSuiteMethodString(), null, false, null); } protected void createMain(IType type) throws JavaModelException { type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null); } /** * Returns the string content for creating a new suite() method. */ 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(); } /** * Returns the new code to be included in a new suite() or which replaces old code in an existing suite(). */ public static String getUpdatableString(Object[] selectedClasses) throws JavaModelException { StringBuffer suite= new StringBuffer(); suite.append(START_MARKER+"\n"); //$NON-NLS-1$ for (int i= 0; i < selectedClasses.length; i++) { if (selectedClasses[i] instanceof IType) { IType testType= (IType) selectedClasses[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"+END_MARKER); //$NON-NLS-1$ return suite.toString(); } private String getUpdatableString() throws JavaModelException { return getUpdatableString(fClassesInSuiteTable.getCheckedElements()); } /** * Runnable for replacing an existing suite() method. */ 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(WizardMessages.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(START_MARKER) --> int start= source.indexOf(START_MARKER); int start= source.toString().indexOf(START_MARKER); if (start > -1) { //using JDK 1.4 //int end= source.toString().indexOf(END_MARKER, start) --> int end= source.indexOf(END_MARKER, start) int end= source.toString().indexOf(END_MARKER, start); if (end > -1) { monitor.subTask(WizardMessages.getString("NewTestSuiteWizPage.createType.updating.suite_method")); //$NON-NLS-1$ monitor.worked(1); end += END_MARKER.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(), WizardMessages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.title"), WizardMessages.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) { String title= WizardMessages.getString("NewTestSuiteWizPage.error_tile"); //$NON-NLS-1$ String message= WizardMessages.getString("NewTestSuiteWizPage.error_message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } } /** * Returns true iff an existing suite() method has been replaced. */ public boolean hasUpdatedExistingClass() { return fUpdatedExistingClassButton; } private IStatus classesInSuiteChanged() { JUnitStatus status= new JUnitStatus(); if (fClassesInSuiteTable.getCheckedElements().length <= 0) status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.classes_in_suite.error.no_testclasses_selected")); //$NON-NLS-1$ return status; } private void updateSelectedClassesLabel() { int noOfClassesChecked= fClassesInSuiteTable.getCheckedElements().length; String key= (noOfClassesChecked==1) ? "NewTestClassWizPage.treeCaption.classSelected" : "NewTestClassWizPage.treeCaption.classesSelected"; //$NON-NLS-1$ //$NON-NLS-2$ fSelectedClassesLabel.setText(WizardMessages.getFormattedString(key, new Integer(noOfClassesChecked))); } protected void createSuiteNameControl(Composite composite, int nColumns) { fSuiteNameLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fSuiteNameLabel.setFont(composite.getFont()); fSuiteNameLabel.setText(WizardMessages.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= GridData.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(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(WizardMessages.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(WizardMessages.getString("NewTestSuiteWizPage.typeName.warning.already_exists")); //$NON-NLS-1$ fMethodStubsButtons.setEnabled(false); return status; } } fMethodStubsButtons.setEnabled(true); return status; } /** * Sets the focus. */ protected void setFocus() { fSuiteNameText.setFocus(); } /** * Sets the classes in <code>elements</code> as checked. */ public void setCheckedElements(Object[] elements) { fClassesInSuiteTable.setCheckedElements(elements); } protected void cannotUpdateSuiteError() { MessageDialog.openError(getShell(), WizardMessages.getString("NewTestSuiteWizPage.cannotUpdateDialog.title"), //$NON-NLS-1$ WizardMessages.getFormattedString("NewTestSuiteWizPage.cannotUpdateDialog.message", new String[] {START_MARKER, END_MARKER})); //$NON-NLS-1$ } private void writeImports(ImportsManager imports) { imports.addImport("junit.framework.Test"); //$NON-NLS-1$ imports.addImport("junit.framework.TestSuite"); //$NON-NLS-1$ } /** * 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)); //The next 2 lines are necessary. Otherwise, if fMethodsStubsButtons is disabled, and USE_TESTRUNNER gets enabled, //then the checkbox for USE_TESTRUNNER will be the only enabled component of fMethodsStubsButton fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled()); fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled()); 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()); } } }
32,180
Bug 32180 keyboard shortcut for sort members
It would be nice to have a keyboard shortcut to sort members.
resolved fixed
fc0eb9c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T14:23:02Z
2003-02-18T23:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateActionGroup.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.ui.actions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.AddBookmarkAction; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.ConvertLineDelimitersAction; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.AddTaskAction; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; /** * Action group that adds the source and generate actions to a part's context * menu and installs handlers for the corresponding global menu actions. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class GenerateActionGroup extends ActionGroup { private CompilationUnitEditor fEditor; private IWorkbenchSite fSite; private String fGroupName= IContextMenuConstants.GROUP_SOURCE; private List fRegisteredSelectionListeners; private AddImportOnSelectionAction fAddImport; private OverrideMethodsAction fOverrideMethods; private AddGetterSetterAction fAddGetterSetter; private AddDelegateMethodsAction fAddDelegateMethods; private AddUnimplementedConstructorsAction fAddUnimplementedConstructors; private AddJavaDocStubAction fAddJavaDocStub; private AddBookmarkAction fAddBookmark; private AddTaskAction fAddTaskAction; private ExternalizeStringsAction fExternalizeStrings; private FindStringsToExternalizeAction fFindStringsToExternalize; private SurroundWithTryCatchAction fSurroundWithTryCatch; private AddToClasspathAction fAddToClasspathAction; private RemoveFromClasspathAction fRemoveFromClasspathAction; private OrganizeImportsAction fOrganizeImports; private SortMembersAction fSortMembers; private ConvertLineDelimitersAction fConvertToWindows; private ConvertLineDelimitersAction fConvertToUNIX; private ConvertLineDelimitersAction fConvertToMac; /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public GenerateActionGroup(CompilationUnitEditor editor, String groupName) { fSite= editor.getSite(); fEditor= editor; fGroupName= groupName; ICompilationUnit input= SelectionConverter.getInputAsCompilationUnit(editor); if (input == null || !JavaModelUtil.isOnClasspath(input)) return; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fAddImport= new AddImportOnSelectionAction(editor); fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT); fAddImport.update(); editor.setAction("AddImport", fAddImport); //$NON-NLS-1$ fOrganizeImports= new OrganizeImportsAction(editor); fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS); editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$ fSortMembers= new SortMembersAction(editor); fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS); editor.setAction("SortMembers", fSortMembers); //$NON-NLS-1$ fOverrideMethods= new OverrideMethodsAction(editor); fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS); editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$ fAddGetterSetter= new AddGetterSetterAction(editor); fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER); editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$ fAddDelegateMethods= new AddDelegateMethodsAction(editor); fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS); editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$ fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor); fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS); editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$ fAddJavaDocStub= new AddJavaDocStubAction(editor); fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor); fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH); fSurroundWithTryCatch.update(selection); provider.addSelectionChangedListener(fSurroundWithTryCatch); editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); //$NON-NLS-1$ fExternalizeStrings= new ExternalizeStringsAction(editor); fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS); editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$ fConvertToWindows= new ConvertLineDelimitersAction(editor, "\r\n"); //$NON-NLS-1$ fConvertToWindows.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS); editor.setAction("ConvertLineDelimitersToWindows", fConvertToWindows); //$NON-NLS-1$ fConvertToUNIX= new ConvertLineDelimitersAction(editor, "\n"); //$NON-NLS-1$ fConvertToUNIX.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_UNIX); editor.setAction("ConvertLineDelimitersToUNIX", fConvertToUNIX); //$NON-NLS-1$ fConvertToMac= new ConvertLineDelimitersAction(editor, "\r"); //$NON-NLS-1$ fConvertToMac.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_MAC); editor.setAction("ConvertLineDelimitersToMac", fConvertToMac); //$NON-NLS-1$ } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the page's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param page the page that owns this action group */ public GenerateActionGroup(Page page) { this(page.getSite()); } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the part's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public GenerateActionGroup(IViewPart part) { this(part.getSite()); } private GenerateActionGroup(IWorkbenchSite site) { fSite= site; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fOverrideMethods= new OverrideMethodsAction(site); fAddGetterSetter= new AddGetterSetterAction(site); fAddDelegateMethods= new AddDelegateMethodsAction(site); fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site); fAddJavaDocStub= new AddJavaDocStubAction(site); fAddBookmark= new AddBookmarkAction(site.getShell()); fAddToClasspathAction= new AddToClasspathAction(site); fRemoveFromClasspathAction= new RemoveFromClasspathAction(site); fAddTaskAction= new AddTaskAction(site); fExternalizeStrings= new ExternalizeStringsAction(site); fFindStringsToExternalize= new FindStringsToExternalizeAction(site); fOrganizeImports= new OrganizeImportsAction(site); fSortMembers= new SortMembersAction(site); fOverrideMethods.update(selection); fAddGetterSetter.update(selection); fAddDelegateMethods.update(selection); fAddUnimplementedConstructors.update(selection); fAddJavaDocStub.update(selection); fExternalizeStrings.update(selection); fFindStringsToExternalize.update(selection); fAddTaskAction.update(selection); fOrganizeImports.update(selection); fSortMembers.update(selection); if (selection instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection)selection; fAddBookmark.selectionChanged(ss); } else { fAddBookmark.setEnabled(false); } registerSelectionListener(provider, fOverrideMethods); registerSelectionListener(provider, fAddGetterSetter); registerSelectionListener(provider, fAddDelegateMethods); registerSelectionListener(provider, fAddUnimplementedConstructors); registerSelectionListener(provider, fAddJavaDocStub); registerSelectionListener(provider, fAddBookmark); registerSelectionListener(provider, fAddToClasspathAction); registerSelectionListener(provider, fRemoveFromClasspathAction); registerSelectionListener(provider, fExternalizeStrings); registerSelectionListener(provider, fFindStringsToExternalize); registerSelectionListener(provider, fOrganizeImports); registerSelectionListener(provider, fSortMembers); registerSelectionListener(provider, fAddTaskAction); } private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) { if (fRegisteredSelectionListeners == null) fRegisteredSelectionListeners= new ArrayList(20); provider.addSelectionChangedListener(listener); fRegisteredSelectionListeners.add(listener); } /* * The state of the editor owning this action group has changed. * This method does nothing if the group's owner isn't an * editor. */ /** * Note: This method is for internal use only. Clients should not call this method. */ public void editorStateChanged() { Assert.isTrue(isEditorOwner()); // http://dev.eclipse.org/bugs/show_bug.cgi?id=17709 fConvertToMac.update(); fConvertToUNIX.update(); fConvertToWindows.update(); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillActionBars(IActionBars actionBar) { super.fillActionBars(actionBar); setGlobalActionHandlers(actionBar); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); if (isEditorOwner()) { IMenuManager subMenu= createEditorSubMenu(menu); if (subMenu != null) menu.appendToGroup(fGroupName, subMenu); } else { appendToGroup(menu, fOrganizeImports); appendToGroup(menu, fOverrideMethods); appendToGroup(menu, fAddGetterSetter); appendToGroup(menu, fAddDelegateMethods); appendToGroup(menu, fAddUnimplementedConstructors); appendToGroup(menu, fAddJavaDocStub); appendToGroup(menu, fAddToClasspathAction); appendToGroup(menu, fRemoveFromClasspathAction); } } private IMenuManager createEditorSubMenu(IMenuManager mainMenu) { IMenuManager result= new MenuManager(ActionMessages.getString("SourceMenu.label")); //$NON-NLS-1$ int added= 0; added+= addEditorAction(result, "Comment"); //$NON-NLS-1$ added+= addEditorAction(result, "Uncomment"); //$NON-NLS-1$ result.add(new Separator()); added+= addAction(result, fOrganizeImports); added+= addAction(result, fAddImport); result.add(new Separator()); added+= addAction(result, fOverrideMethods); added+= addAction(result, fAddGetterSetter); added+= addAction(result, fAddDelegateMethods); added+= addAction(result, fAddUnimplementedConstructors); added+= addAction(result, fAddJavaDocStub); added+= addEditorAction(result, "Format"); //$NON-NLS-1$ added+= addAction(result, fSortMembers); added+= addAction(result, fAddBookmark); result.add(new Separator()); added+= addAction(result, fSurroundWithTryCatch); added+= addAction(result, fExternalizeStrings); if (added == 0) result= null; return result; } /* (non-Javadoc) * Method declared in ActionGroup */ public void dispose() { if (fRegisteredSelectionListeners != null) { ISelectionProvider provider= fSite.getSelectionProvider(); for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) { ISelectionChangedListener listener= (ISelectionChangedListener) iter.next(); provider.removeSelectionChangedListener(listener); } } fEditor= null; super.dispose(); } private void setGlobalActionHandlers(IActionBars actionBar) { actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport); actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatch); actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub); actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings); actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize); actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports); actionBar.setGlobalActionHandler(JdtActionConstants.SORT_MEMBERS, fSortMembers); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_WINDOWS, fConvertToWindows); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_UNIX, fConvertToUNIX); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_MAC, fConvertToMac); if (!isEditorOwner()) { // editor provides its own implementation of these actions. actionBar.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmark); actionBar.setGlobalActionHandler(IWorkbenchActionConstants.ADD_TASK, fAddTaskAction); } } private int appendToGroup(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.appendToGroup(fGroupName, action); return 1; } return 0; } private int addAction(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.add(action); return 1; } return 0; } private int addEditorAction(IMenuManager menu, String actionID) { if (fEditor == null) return 0; IAction action= fEditor.getAction(actionID); if (action == null) return 0; if (action instanceof IUpdate) ((IUpdate)action).update(); if (action.isEnabled()) { menu.add(action); return 1; } return 0; } private boolean isEditorOwner() { return fEditor != null; } }
32,180
Bug 32180 keyboard shortcut for sort members
It would be nice to have a keyboard shortcut to sort members.
resolved fixed
fc0eb9c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T14:23:02Z
2003-02-18T23:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/IJavaEditorActionDefinitionIds.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.ui.actions; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; /** * Defines the definition IDs for the Java editor actions. * * <p> * This interface is not intended to be implemented or extended. * </p>. * * @since 2.0 */ public interface IJavaEditorActionDefinitionIds extends ITextEditorActionDefinitionIds { // edit /** * Action definition ID of the edit -> go to matching bracket action * (value <code>"org.eclipse.jdt.ui.edit.text.java.goto.matching.bracket"</code>). * * @since 2.1 */ public static final String GOTO_MATCHING_BRACKET= "org.eclipse.jdt.ui.edit.text.java.goto.matching.bracket"; //$NON-NLS-1$ /** * Action definition ID of the edit -> go to next member action * (value <code>"org.eclipse.jdt.ui.edit.text.java.goto.next.member"</code>). * * @since 2.1 */ public static final String GOTO_NEXT_MEMBER= "org.eclipse.jdt.ui.edit.text.java.goto.next.member"; //$NON-NLS-1$ /** * Action definition ID of the edit -> go to previous member action * (value <code>"org.eclipse.jdt.ui.edit.text.java.goto.previous.member"</code>). * * @since 2.1 */ public static final String GOTO_PREVIOUS_MEMBER= "org.eclipse.jdt.ui.edit.text.java.goto.previous.member"; //$NON-NLS-1$ /** * Action definition ID of the edit -> select enclosing action * (value <code>"org.eclipse.jdt.ui.edit.text.java.select.enclosing"</code>). */ public static final String SELECT_ENCLOSING= "org.eclipse.jdt.ui.edit.text.java.select.enclosing"; //$NON-NLS-1$ /** * Action definition ID of the edit -> select next action * (value <code>"org.eclipse.jdt.ui.edit.text.java.select.next"</code>). */ public static final String SELECT_NEXT= "org.eclipse.jdt.ui.edit.text.java.select.next"; //$NON-NLS-1$ /** * Action definition ID of the edit -> select previous action * (value <code>"org.eclipse.jdt.ui.edit.text.java.select.previous"</code>). */ public static final String SELECT_PREVIOUS= "org.eclipse.jdt.ui.edit.text.java.select.previous"; //$NON-NLS-1$ /** * Action definition ID of the edit -> select restore last action * (value <code>"org.eclipse.jdt.ui.edit.text.java.select.last"</code>). */ public static final String SELECT_LAST= "org.eclipse.jdt.ui.edit.text.java.select.last"; //$NON-NLS-1$ /** * Action definition ID of the edit -> correction assist proposal action * (value <code>"org.eclipse.jdt.ui.edit.text.java.correction.assist.proposals"</code>). */ public static final String CORRECTION_ASSIST_PROPOSALS= "org.eclipse.jdt.ui.edit.text.java.correction.assist.proposals"; //$NON-NLS-1$ /** * Action definition ID of the edit -> show Javadoc action * (value <code>"org.eclipse.jdt.ui.edit.text.java.show.javadoc"</code>). */ public static final String SHOW_JAVADOC= "org.eclipse.jdt.ui.edit.text.java.show.javadoc"; //$NON-NLS-1$ /** * Action definition ID of the edit -> Show Outline action * (value <code>"org.eclipse.jdt.ui.edit.text.java.show.outline"</code>). */ public static final String SHOW_OUTLINE= "org.eclipse.jdt.ui.edit.text.java.show.outline"; //$NON-NLS-1$ /** * Action definition ID of the Navigate -> Open Structure action * (value <code>"org.eclipse.jdt.ui.navigate.java.open.structure"</code>). */ public static final String OPEN_STRUCTURE= "org.eclipse.jdt.ui.navigate.java.open.structure"; //$NON-NLS-1$ // source /** * Action definition ID of the source -> comment action * (value <code>"org.eclipse.jdt.ui.edit.text.java.comment"</code>). */ public static final String COMMENT= "org.eclipse.jdt.ui.edit.text.java.comment"; //$NON-NLS-1$ /** * Action definition ID of the source -> uncomment action * (value <code>"org.eclipse.jdt.ui.edit.text.java.uncomment"</code>). */ public static final String UNCOMMENT= "org.eclipse.jdt.ui.edit.text.java.uncomment"; //$NON-NLS-1$ /** * Action definition ID of the source -> format action * (value <code>"org.eclipse.jdt.ui.edit.text.java.format"</code>). */ public static final String FORMAT= "org.eclipse.jdt.ui.edit.text.java.format"; //$NON-NLS-1$ /** * Action definition ID of the source -> add import action * (value <code>"org.eclipse.jdt.ui.edit.text.java.add.import"</code>). */ public static final String ADD_IMPORT= "org.eclipse.jdt.ui.edit.text.java.add.import"; //$NON-NLS-1$ /** * Action definition ID of the source -> organize imports action * (value <code>"org.eclipse.jdt.ui.edit.text.java.organize.imports"</code>). */ public static final String ORGANIZE_IMPORTS= "org.eclipse.jdt.ui.edit.text.java.organize.imports"; //$NON-NLS-1$ /** * Action definition ID of the source -> sort order action (value * <code>"org. eclipse. jdt.ui.edit.text.java.sort.members"</code>). * @since 2.1 */ public static final String SORT_MEMBERS= "org.eclipse.jdt.ui.edit.text.java.sort.members"; //$NON-NLS-1$ /** * Action definition ID of the source -> surround with try/catch action * (value <code>"org.eclipse.jdt.ui.edit.text.java.surround.with.try.catch"</code>). */ public static final String SURROUND_WITH_TRY_CATCH= "org.eclipse.jdt.ui.edit.text.java.surround.with.try.catch"; //$NON-NLS-1$ /** * Action definition ID of the source -> override methods action * (value <code>"org.eclipse.jdt.ui.edit.text.java.override.methods"</code>). */ public static final String OVERRIDE_METHODS= "org.eclipse.jdt.ui.edit.text.java.override.methods"; //$NON-NLS-1$ /** * Action definition ID of the source -> add unimplemented constructors action * (value <code>"org.eclipse.jdt.ui.edit.text.java.add.unimplemented.constructors"</code>). */ public static final String ADD_UNIMPLEMENTED_CONTRUCTORS= "org.eclipse.jdt.ui.edit.text.java.add.unimplemented.constructors"; //$NON-NLS-1$ /** * Action definition ID of the source -> generate setter/getter action * (value <code>"org.eclipse.jdt.ui.edit.text.java.create.getter.setter"</code>). */ public static final String CREATE_GETTER_SETTER= "org.eclipse.jdt.ui.edit.text.java.create.getter.setter"; //$NON-NLS-1$ /** * Action definition ID of the source -> generate delegates action (value * <code>"org.eclipse.jdt.ui.edit.text.java.create.delegate.methods"</code>). * @since 2.1 */ public static final String CREATE_DELEGATE_METHODS= "org.eclipse.jdt.ui.edit.text.java.create.delegate.methods"; //$NON-NLS-1$ /** * Action definition ID of the source -> externalize strings action * (value <code>"org.eclipse.jdt.ui.edit.text.java.externalize.strings"</code>). */ public static final String EXTERNALIZE_STRINGS= "org.eclipse.jdt.ui.edit.text.java.externalize.strings"; //$NON-NLS-1$ /** * Note: this id is for internal use only. */ public static final String SHOW_NEXT_PROBLEM= "org.eclipse.jdt.ui.edit.text.java.show.next.problem"; //$NON-NLS-1$ /** * Note: this id is for internal use only. */ public static final String SHOW_PREVIOUS_PROBLEM= "org.eclipse.jdt.ui.edit.text.java.show.previous.problem"; //$NON-NLS-1$ // refactor /** * Action definition ID of the refactor -> pull up action * (value <code>"org.eclipse.jdt.ui.edit.text.java.pull.up"</code>). */ public static final String PULL_UP= "org.eclipse.jdt.ui.edit.text.java.pull.up"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> push down action (value * <code>"org. eclipse.jdt.ui.edit.text.java.push.down"</code>). * * @since 2.1 */ public static final String PUSH_DOWN= "org.eclipse.jdt.ui.edit.text.java.push.down"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> rename element action * (value <code>"org.eclipse.jdt.ui.edit.text.java.rename.element"</code>). */ public static final String RENAME_ELEMENT= "org.eclipse.jdt.ui.edit.text.java.rename.element"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> modify method parameters action * (value <code>"org.eclipse.jdt.ui.edit.text.java.modify.method.parameters"</code>). */ public static final String MODIFY_METHOD_PARAMETERS= "org.eclipse.jdt.ui.edit.text.java.modify.method.parameters"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> move element action * (value <code>"org.eclipse.jdt.ui.edit.text.java.move.element"</code>). */ public static final String MOVE_ELEMENT= "org.eclipse.jdt.ui.edit.text.java.move.element"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> extract local variable action * (value <code>"org.eclipse.jdt.ui.edit.text.java.extract.local.variable"</code>). */ public static final String EXTRACT_LOCAL_VARIABLE= "org.eclipse.jdt.ui.edit.text.java.extract.local.variable"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> extract constant action * (value <code>"org.eclipse.jdt.ui.edit.text.java.extract.constant"</code>). * * @since 2.1 */ public static final String EXTRACT_CONSTANT= "org.eclipse.jdt.ui.edit.text.java.extract.constant"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> inline local variable action * (value <code>"org.eclipse.jdt.ui.edit.text.java.inline.local.variable"</code>). * @deprecated Use INLINE */ public static final String INLINE_LOCAL_VARIABLE= "org.eclipse.jdt.ui.edit.text.java.inline.local.variable"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> self encapsulate field action * (value <code>"org.eclipse.jdt.ui.edit.text.java.self.encapsulate.field"</code>). */ public static final String SELF_ENCAPSULATE_FIELD= "org.eclipse.jdt.ui.edit.text.java.self.encapsulate.field"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> extract method action * (value <code>"org.eclipse.jdt.ui.edit.text.java.extract.method"</code>). */ public static final String EXTRACT_METHOD= "org.eclipse.jdt.ui.edit.text.java.extract.method"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> inline action * (value <code>"org. eclipse.jdt.ui.edit.text.java.inline"</code>). * * @since 2.1 */ public static final String INLINE= "org.eclipse.jdt.ui.edit.text.java.inline"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> extract interface action * (value <code>"org.eclipse.jdt.ui.edit.text.java.extract.interface"</code>). * * @since 2.1 */ public static final String EXTRACT_INTERFACE= "org.eclipse.jdt.ui.edit.text.java.extract.interface"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> move inner type to top level action * (value <code>"org.eclipse.jdt.ui.edit.text.java.move.inner.to.top.level"</code>). * * @since 2.1 */ public static final String MOVE_INNER_TO_TOP= "org.eclipse.jdt.ui.edit.text.java.move.inner.to.top.level"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> use supertype action * (value <code>"org.eclipse.jdt.ui.edit.text.java.use.supertype"</code>). * * @since 2.1 */ public static final String USE_SUPERTYPE= "org.eclipse.jdt.ui.edit.text.java.use.supertype"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> promote local variable action * (value <code>"org.eclipse.jdt.ui.edit.text.java.promote.local.variable"</code>). * * @since 2.1 */ public static final String PROMOTE_LOCAL_VARIABLE= "org.eclipse.jdt.ui.edit.text.java.promote.local.variable"; //$NON-NLS-1$ /** * Action definition ID of the refactor -> convert anonynous to nested action * (value <code>"org.eclipse.jdt.ui.edit.text.java.convert.anonymous.to.nested"</code>). * * @since 2.1 */ public static final String CONVERT_ANONYMOUS_TO_NESTED= "org.eclipse.jdt.ui.edit.text.java.convert.anonymous.to.nested"; //$NON-NLS-1$ // navigate /** * Action definition ID of the navigate -> open action * (value <code>"org.eclipse.jdt.ui.edit.text.java.open.editor"</code>). */ public static final String OPEN_EDITOR= "org.eclipse.jdt.ui.edit.text.java.open.editor"; //$NON-NLS-1$ /** * Action definition ID of the navigate -> open super implementation action * (value <code>"org.eclipse.jdt.ui.edit.text.java.open.super.implementation"</code>). */ public static final String OPEN_SUPER_IMPLEMENTATION= "org.eclipse.jdt.ui.edit.text.java.open.super.implementation"; //$NON-NLS-1$ /** * Action definition ID of the navigate -> open external javadoc action * (value <code>"org.eclipse.jdt.ui.edit.text.java.open.external.javadoc"</code>). */ public static final String OPEN_EXTERNAL_JAVADOC= "org.eclipse.jdt.ui.edit.text.java.open.external.javadoc"; //$NON-NLS-1$ /** * Action definition ID of the navigate -> open type hierarchy action * (value <code>"org.eclipse.jdt.ui.edit.text.java.org.eclipse.jdt.ui.edit.text.java.open.type.hierarchy"</code>). */ public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.edit.text.java.open.type.hierarchy"; //$NON-NLS-1$ /** * Action definition ID of the navigate -> show in package explorer action * (value <code>"org.eclipse.jdt.ui.edit.text.java.show.in.package.view"</code>). */ public static final String SHOW_IN_PACKAGE_VIEW= "org.eclipse.jdt.ui.edit.text.java.show.in.package.view"; //$NON-NLS-1$ /** * Action definition ID of the navigate -> show in navigator action * (value <code>"org.eclipse.jdt.ui.edit.text.java.show.in.navigator.view"</code>). */ public static final String SHOW_IN_NAVIGATOR_VIEW= "org.eclipse.jdt.ui.edit.text.java.show.in.navigator.view"; //$NON-NLS-1$ // search /** * Action definition ID of the search -> references in workspace action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.references.in.workspace"</code>). */ public static final String SEARCH_REFERENCES_IN_WORKSPACE= "org.eclipse.jdt.ui.edit.text.java.search.references.in.workspace"; //$NON-NLS-1$ /** * Action definition ID of the search -> references in hierarchy action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.references.in.hierarchy"</code>). */ public static final String SEARCH_REFERENCES_IN_HIERARCHY= "org.eclipse.jdt.ui.edit.text.java.search.references.in.hierarchy"; //$NON-NLS-1$ /** * Action definition ID of the search -> references in working set action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.references.in.working.set"</code>). */ public static final String SEARCH_REFERENCES_IN_WORKING_SET= "org.eclipse.jdt.ui.edit.text.java.search.references.in.working.set"; //$NON-NLS-1$ /** * Action definition ID of the search -> read access in workspace action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.read.access.in.workspace"</code>). */ public static final String SEARCH_READ_ACCESS_IN_WORKSPACE= "org.eclipse.jdt.ui.edit.text.java.search.read.access.in.workspace"; //$NON-NLS-1$ /** * Action definition ID of the search -> read access in hierarchy action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.read.access.in.hierarchy"</code>). */ public static final String SEARCH_READ_ACCESS_IN_HIERARCHY= "org.eclipse.jdt.ui.edit.text.java.search.read.access.in.hierarchy"; //$NON-NLS-1$ /** * Action definition ID of the search -> read access in working set action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.read.access.in.working.set"</code>). */ public static final String SEARCH_READ_ACCESS_IN_WORKING_SET= "org.eclipse.jdt.ui.edit.text.java.search.read.access.in.working.set"; //$NON-NLS-1$ /** * Action definition ID of the search -> write access in workspace action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.write.access.in.workspace"</code>). */ public static final String SEARCH_WRITE_ACCESS_IN_WORKSPACE= "org.eclipse.jdt.ui.edit.text.java.search.write.access.in.workspace"; //$NON-NLS-1$ /** * Action definition ID of the search -> write access in hierarchy action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.write.access.in.hierarchy"</code>). */ public static final String SEARCH_WRITE_ACCESS_IN_HIERARCHY= "org.eclipse.jdt.ui.edit.text.java.search.write.access.in.hierarchy"; //$NON-NLS-1$ /** * Action definition ID of the search -> write access in working set action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.write.access.in.working.set"</code>). */ public static final String SEARCH_WRITE_ACCESS_IN_WORKING_SET= "org.eclipse.jdt.ui.edit.text.java.search.write.access.in.working.set"; //$NON-NLS-1$ /** * Action definition ID of the search -> declarations in workspace action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.declarations.in.workspace"</code>). */ public static final String SEARCH_DECLARATIONS_IN_WORKSPACE= "org.eclipse.jdt.ui.edit.text.java.search.declarations.in.workspace"; //$NON-NLS-1$ /** * Action definition ID of the search -> declarations in hierarchy action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.declarations.in.hierarchy"</code>). */ public static final String SEARCH_DECLARATIONS_IN_HIERARCHY= "org.eclipse.jdt.ui.edit.text.java.search.declarations.in.hierarchy"; //$NON-NLS-1$ /** * Action definition ID of the search -> declarations in working set action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.declarations.in.working.set"</code>). */ public static final String SEARCH_DECLARATIONS_IN_WORKING_SET= "org.eclipse.jdt.ui.edit.text.java.search.declarations.in.working.set"; //$NON-NLS-1$ /** * Action definition ID of the search -> implementors in workspace action * (value <code>"org.eclipse.jdt.ui.edit.text.java.search.implementors.in.workspace"</code>). */ public static final String SEARCH_IMPLEMENTORS_IN_WORKSPACE= "org.eclipse.jdt.ui.edit.text.java.search.implementors.in.workspace"; //$NON-NLS-1$ /** * Action definition ID of the search -> implementors in working set action * (value <code>"org.eclipse.jdt.ui.edit.text.java.seach.implementors.in.working.set"</code>). */ public static final String SEARCH_IMPLEMENTORS_IN_WORKING_SET= "org.eclipse.jdt.ui.edit.text.java.seach.implementors.in.working.set"; //$NON-NLS-1$ // miscellaneous /** * Action definition ID of the toggle presentation toolbar button action * (value <code>"org.eclipse.jdt.ui.edit.text.java.toggle.presentation"</code>). */ public static final String TOGGLE_PRESENTATION= "org.eclipse.jdt.ui.edit.text.java.toggle.presentation"; //$NON-NLS-1$ /** * Action definition ID of the toggle text hover toolbar button action * (value <code>"org.eclipse.jdt.ui.edit.text.java.toggle.text.hover"</code>). */ public static final String TOGGLE_TEXT_HOVER= "org.eclipse.jdt.ui.edit.text.java.toggle.text.hover"; //$NON-NLS-1$ }
29,755
Bug 29755 Attach source does not allow one to select a folder... [build path]
When opening some .class that does not yet have a source attachment eclipse shows a text version of the interface defintion and a button for Attaching source. When pressing this button a window appaer where one can enter the name/location of a folder, zip or jar for the source. There are also a button for choosing it via a file selection dialog and this works fine for zip and jar files - but not for selecting a directory :( Workaround is just to enter the directory manually.
resolved fixed
98adbab
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:03:58Z
2003-01-18T14:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; 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.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.ClasspathContainerInitializer; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; 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.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; /** * UI to set the source attachment archive and root. * Same implementation for both setting attachments for libraries from * variable entries and for normal (internal or external) jar. */ public class SourceAttachmentBlock { private static class UpdatedClasspathContainer implements IClasspathContainer { private IClasspathEntry[] fNewEntries; private IClasspathContainer fOriginal; public UpdatedClasspathContainer(IClasspathContainer original, IClasspathEntry[] newEntries) { fNewEntries= newEntries; fOriginal= original; } public IClasspathEntry[] getClasspathEntries() { return fNewEntries; } public String getDescription() { return fOriginal.getDescription(); } public int getKind() { return fOriginal.getKind(); } public IPath getPath() { return fOriginal.getPath(); } } private IStatusChangeListener fContext; private StringButtonDialogField fFileNameField; private SelectionButtonDialogField fInternalButtonField; private IStatus fNameStatus; /** * The file to which the archive path points to. * Only set when the file exists. */ private File fResolvedFile; /** * The path to which the archive variable points. * Null if invalid path or not resolvable. Must not exist. */ private IPath fFileVariablePath; private IWorkspaceRoot fWorkspaceRoot; private Control fSWTWidget; private CLabel fFullPathResolvedLabel; private IJavaProject fProject; private IClasspathEntry fEntry; private IPath fContainerPath; /** * @deprecated */ public SourceAttachmentBlock(IWorkspaceRoot root, IStatusChangeListener context, IClasspathEntry oldEntry) { this(context, oldEntry, null, null); } /** * @param context listeners for status updates * @param entryToEdit The entry to edit * @param containerPath Path of the container that contains the given entry or * <code>null</code> if the entry does not belong to a container. * @param project Project to which the entry belongs. Can be * <code>null</code> if <code>getRunnable</code> is not run and the entry * does not belong to a container. * */ public SourceAttachmentBlock(IStatusChangeListener context, IClasspathEntry entry, IPath containerPath, IJavaProject project) { Assert.isNotNull(entry); fContext= context; fEntry= entry; fContainerPath= containerPath; fProject= project; int kind= entry.getEntryKind(); Assert.isTrue(kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE); fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); fNameStatus= new StatusInfo(); SourceAttachmentAdapter adapter= new SourceAttachmentAdapter(); // create the dialog fields (no widgets yet) if (isVariableEntry()) { fFileNameField= new VariablePathDialogField(adapter); fFileNameField.setDialogFieldListener(adapter); fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.varlabel")); //$NON-NLS-1$ fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.varbutton")); //$NON-NLS-1$ ((VariablePathDialogField)fFileNameField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.variable.button")); //$NON-NLS-1$ } else { fFileNameField= new StringButtonDialogField(adapter); fFileNameField.setDialogFieldListener(adapter); fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.label")); //$NON-NLS-1$ fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.button")); //$NON-NLS-1$ fInternalButtonField= new SelectionButtonDialogField(SWT.PUSH); fInternalButtonField.setDialogFieldListener(adapter); fInternalButtonField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.internal.button")); //$NON-NLS-1$ } // set the old settings setDefaults(); } public void setDefaults() { if (fEntry.getSourceAttachmentPath() != null) { fFileNameField.setText(fEntry.getSourceAttachmentPath().toString()); } else { fFileNameField.setText(""); //$NON-NLS-1$ } } private boolean isVariableEntry() { return fEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE; } /** * Gets the source attachment path chosen by the user */ public IPath getSourceAttachmentPath() { if (fFileNameField.getText().length() == 0) { return null; } return new Path(fFileNameField.getText()); } /** * Gets the source attachment root chosen by the user * Returns null to let JCore automatically detect the root. */ public IPath getSourceAttachmentRootPath() { return null; } /** * Creates the control */ public Control createControl(Composite parent) { PixelConverter converter= new PixelConverter(parent); fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 4; composite.setLayout(layout); int widthHint= converter.convertWidthInCharsToPixels(isVariableEntry() ? 50 : 60); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 4; Label message= new Label(composite, SWT.LEFT); message.setLayoutData(gd); message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fEntry.getPath().lastSegment())); //$NON-NLS-1$ if (isVariableEntry()) { DialogField.createEmptySpace(composite, 1); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= widthHint; gd.horizontalSpan= 2; Label desc= new Label(composite, SWT.LEFT + SWT.WRAP); desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.filename.description")); //$NON-NLS-1$ desc.setLayoutData(gd); DialogField.createEmptySpace(composite, 1); } // archive name field fFileNameField.doFillIntoGrid(composite, 4); LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint); LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null)); if (!isVariableEntry()) { // aditional 'browse workspace' button for normal jars DialogField.createEmptySpace(composite, 3); fInternalButtonField.doFillIntoGrid(composite, 1); } else { // label that shows the resolved path for variable jars DialogField.createEmptySpace(composite, 1); fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT); fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); fFullPathResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(composite, 2); } fFileNameField.postSetFocusOnDialogField(parent.getDisplay()); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK); return composite; } private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { attachmentChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { attachmentDialogFieldChanged(field); } } private void attachmentChangeControlPressed(DialogField field) { if (field == fFileNameField) { IPath jarFilePath= chooseExtJarFile(); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } } } // ---------- IDialogFieldListener -------- private void attachmentDialogFieldChanged(DialogField field) { if (field == fFileNameField) { fNameStatus= updateFileNameStatus(); } else if (field == fInternalButtonField) { IPath jarFilePath= chooseInternalJarFile(); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } return; } doStatusLineUpdate(); } private void doStatusLineUpdate() { fFileNameField.enableButton(canBrowseFileName()); // set the resolved path for variable jars if (fFullPathResolvedLabel != null) { fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); } IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus }); fContext.statusChanged(status); } private boolean canBrowseFileName() { if (!isVariableEntry()) { return true; } // to browse with a variable JAR, the variable name must point to a directory if (fFileVariablePath != null) { return fFileVariablePath.toFile().isDirectory(); } return false; } private String getResolvedLabelString(String path, boolean osPath) { IPath resolvedPath= getResolvedPath(new Path(path)); if (resolvedPath != null) { if (osPath) { return resolvedPath.toOSString(); } else { return resolvedPath.toString(); } } return ""; //$NON-NLS-1$ } private IPath getResolvedPath(IPath path) { if (path != null) { String varName= path.segment(0); if (varName != null) { IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { return varPath.append(path.removeFirstSegments(1)); } } } return null; } private IStatus updateFileNameStatus() { StatusInfo status= new StatusInfo(); fResolvedFile= null; fFileVariablePath= null; String fileName= fFileNameField.getText(); if (fileName.length() == 0) { // no source attachment return status; } else { if (!Path.EMPTY.isValidPath(fileName)) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$ return status; } IPath filePath= new Path(fileName); IPath resolvedPath; if (isVariableEntry()) { if (filePath.getDevice() != null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.deviceinpath")); //$NON-NLS-1$ return status; } String varName= filePath.segment(0); if (varName == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$ return status; } fFileVariablePath= JavaCore.getClasspathVariable(varName); if (fFileVariablePath == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.varnotexists")); //$NON-NLS-1$ return status; } resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1)); if (resolvedPath.isEmpty()) { status.setWarning(NewWizardMessages.getString("SourceAttachmentBlock.filename.warning.varempty")); //$NON-NLS-1$ return status; } File file= resolvedPath.toFile(); if (!file.exists()) { String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", resolvedPath.toOSString()); //$NON-NLS-1$ status.setWarning(message); return status; } fResolvedFile= file; } else { File file= filePath.toFile(); IResource res= fWorkspaceRoot.findMember(filePath); if (res != null && res.getLocation() != null) { file= res.getLocation().toFile(); } if (!file.exists()) { String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", filePath.toString()); //$NON-NLS-1$ status.setError(message); return status; } fResolvedFile= file; } } return status; } /* * Opens a dialog to choose a jar from the file system. */ private IPath chooseExtJarFile() { IPath currPath= new Path(fFileNameField.getText()); if (currPath.isEmpty()) { currPath= fEntry.getPath(); } if (isVariableEntry()) { IPath resolvedPath= getResolvedPath(currPath); File initialSelection= resolvedPath != null ? resolvedPath.toFile() : null; String currVariable= currPath.segment(0); JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), false, true); dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.extvardialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.extvardialog.description")); //$NON-NLS-1$ dialog.setInput(fFileVariablePath.toFile()); dialog.setInitialSelection(initialSelection); if (dialog.open() == JARFileSelectionDialog.OK) { File result= (File) dialog.getResult()[0]; IPath returnPath= new Path(result.getPath()).makeAbsolute(); return modifyPath(returnPath, currVariable); } } else { if (ArchiveFileFilter.isArchivePath(currPath)) { currPath= currPath.removeLastSegments(1); } FileDialog dialog= new FileDialog(getShell()); dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.extjardialog.text")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(currPath.toOSString()); String res= dialog.open(); if (res != null) { return new Path(res).makeAbsolute(); } } return null; } /* * Opens a dialog to choose an internal jar. */ private IPath chooseInternalJarFile() { String initSelection= fFileNameField.getText(); Class[] acceptedClasses= new Class[] { IFolder.class, IFile.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); ViewerFilter filter= new ArchiveFileFilter(null, false); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSel= null; if (initSelection.length() > 0) { initSel= fWorkspaceRoot.findMember(new Path(initSelection)); } if (initSel == null) { initSel= fWorkspaceRoot.findMember(fEntry.getPath()); } FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp); dialog.setAllowMultiple(false); dialog.setValidator(validator); dialog.addFilter(filter); dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.message")); //$NON-NLS-1$ dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSel); if (dialog.open() == ElementTreeSelectionDialog.OK) { IResource res= (IResource) dialog.getFirstResult(); return res.getFullPath(); } return null; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Takes a path and replaces the beginning with a variable name * (if the beginning matches with the variables value) */ private IPath modifyPath(IPath path, String varName) { if (varName == null || path == null) { return null; } if (path.isEmpty()) { return new Path(varName); } IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { if (varPath.isPrefixOf(path)) { path= path.removeFirstSegments(varPath.segmentCount()); } else { path= new Path(path.lastSegment()); } } else { path= new Path(path.lastSegment()); } return new Path(varName).append(path); } /** * Creates a runnable that sets the source attachment by modifying the project's classpath. * @deprecated use getRunnable() instead */ public IRunnableWithProgress getRunnable(final IJavaProject jproject, final Shell shell) { fProject= jproject; return getRunnable(shell); } /** * Creates a runnable that sets the source attachment by modifying the * project's classpath or updating a container. */ public IRunnableWithProgress getRunnable(final Shell shell) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { attachSource(shell, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } protected void attachSource(final Shell shell, IProgressMonitor monitor) throws CoreException { boolean isExported= fEntry.isExported(); IClasspathEntry newEntry; if (fEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { newEntry= JavaCore.newVariableEntry(fEntry.getPath(), getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported); } else { newEntry= JavaCore.newLibraryEntry(fEntry.getPath(), getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported); } if (fContainerPath != null) { updateContainerClasspath(fProject, fContainerPath, newEntry, monitor); } else { updateProjectClasspath(shell, fProject, newEntry, monitor); } } private void updateContainerClasspath(IJavaProject jproject, IPath containerPath, IClasspathEntry newEntry, IProgressMonitor monitor) throws CoreException { IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject); IClasspathEntry[] entries= container.getClasspathEntries(); IClasspathEntry[] newEntries= new IClasspathEntry[entries.length]; for (int i= 0; i < entries.length; i++) { IClasspathEntry curr= entries[i]; if (curr.getEntryKind() == newEntry.getEntryKind() && curr.getPath().equals(newEntry.getPath())) { newEntries[i]= newEntry; } else { newEntries[i]= curr; } } IClasspathContainer updatedContainer= new UpdatedClasspathContainer(container, newEntries); ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0)); initializer.requestClasspathContainerUpdate(containerPath, jproject, updatedContainer); monitor.worked(1); } private void updateProjectClasspath(Shell shell, IJavaProject jproject, IClasspathEntry newEntry, IProgressMonitor monitor) throws JavaModelException { IClasspathEntry[] oldClasspath= jproject.getRawClasspath(); int nEntries= oldClasspath.length; ArrayList newEntries= new ArrayList(nEntries + 1); int entryKind= newEntry.getEntryKind(); IPath jarPath= newEntry.getPath(); boolean found= false; for (int i= 0; i < nEntries; i++) { IClasspathEntry curr= oldClasspath[i]; if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) { // add modified entry newEntries.add(newEntry); found= true; } else { newEntries.add(curr); } } if (!found) { if (newEntry.getSourceAttachmentPath() == null || !putJarOnClasspathDialog(shell)) { return; } // add new newEntries.add(newEntry); } IClasspathEntry[] newClasspath= (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]); jproject.setRawClasspath(newClasspath, monitor); } private boolean putJarOnClasspathDialog(Shell shell) { final boolean[] result= new boolean[1]; shell.getDisplay().syncExec(new Runnable() { public void run() { String title= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.message"); //$NON-NLS-1$ result[0]= MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, message); } }); return result[0]; } }
29,458
Bug 29458 Templates for constructor
When I have an existing constructor within a class, which has a single line comment and I attempt to convert this comment to a multi lie comment, it inserts the 'typecomment' tempalte. In addition, the comment is not correctly indented. For example: before: /** * My typecomment */ public class MyClass { /** my constructor */ public MyClass() { } } after (placing cursor before 'my contructor' and hitting enter): /** * My typecomment */ public class MyClass { /** * My typecomment */ my constructor */ public MyClass() { } }
resolved fixed
61c7953
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:23:21Z
2003-01-14T18:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.text.javadoc; import java.text.BreakIterator; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.TextUtilities; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationMessages; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Auto indent strategy for java doc comments */ public class JavaDocAutoIndentStrategy extends DefaultAutoIndentStrategy { public JavaDocAutoIndentStrategy() { } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { JavaPlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } /** * Copies the indentation of the previous line and add a star. * If the javadoc just started on this line add standard method tags * and close the javadoc. * * @param d the document to work on * @param c the command to deal with */ private void jdocIndentAfterNewLine(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { // find start of line int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); IRegion info= d.getLineInformationOfOffset(p); int start= info.getOffset(); // find white spaces int end= findEndOfWhiteSpace(d, start, c.offset); StringBuffer buf= new StringBuffer(c.text); if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness not work for class comments // append to input String indentation= jdocExtractLinePrefix(d, d.getLineOfOffset(c.offset)); buf.append(indentation); if (end < c.offset) { if (d.getChar(end) == '/') { // javadoc started on this line buf.append(" * "); //$NON-NLS-1$ if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) && isNewComment(d, c.offset)) { String lineDelimiter= getLineDelimiter(d); c.doit= false; d.replace(c.offset, 0, lineDelimiter + indentation + " */"); //$NON-NLS-1$ // evaluate method signature ICompilationUnit unit= getCompilationUnit(); if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) && unit != null) { try { unit.reconcile(); String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit); if (string != null) d.replace(c.offset, 0, string); } catch (CoreException e) { // ignore } } } } } } c.text= buf.toString(); } catch (BadLocationException excp) { // stop work } } private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit) throws CoreException, BadLocationException { IJavaElement element= unit.getElementAt(command.offset); if (element == null) return null; switch (element.getElementType()) { case IJavaElement.TYPE: return createTypeTags(document, command, indentation, lineDelimiter, (IType) element); case IJavaElement.METHOD: return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element); default: return null; } } /* * Removes start and end of a comment and corrects indentation and line delimiters. */ private String prepareTemplateComment(String comment, String indentation, String lineDelimiter) { // trim comment start and end if any if (comment.endsWith("*/")) //$NON-NLS-1$ comment= comment.substring(0, comment.length() - 2); comment= comment.trim(); if (comment.startsWith("/*")) { //$NON-NLS-1$ if (comment.length() > 2 && comment.charAt(2) == '*') { comment= comment.substring(3); // remove '/**' } else { comment= comment.substring(2); // remove '/*' } } return Strings.changeIndent(comment, 0, CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter); } private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IType type) throws CoreException, BadLocationException { String comment= StubUtility.getTypeComment(type); if (comment != null) { comment= prepareTemplateComment(comment.trim(), indentation, lineDelimiter); } return (comment == null || comment.length() == 0) ? CodeGenerationMessages.getString("AddJavaDocStubOperation.configure.message") //$NON-NLS-1$ : comment; } private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method) throws CoreException, BadLocationException { IRegion partition= document.getPartition(command.offset); ISourceRange sourceRange= method.getSourceRange(); if (sourceRange == null || sourceRange.getOffset() != partition.getOffset()) return null; IMethod inheritedMethod= getInheritedMethod(method); String comment= StubUtility.getMethodComment(method, inheritedMethod); if (comment != null) { comment= comment.trim(); boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$ boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$ if (javadocComment == isJavaDoc) { return prepareTemplateComment(comment, indentation, lineDelimiter); } } return null; } /** * Returns the method inherited from, <code>null</code> if method is newly defined. */ private static IMethod getInheritedMethod(IMethod method) throws JavaModelException { IType declaringType= method.getDeclaringType(); ITypeHierarchy typeHierarchy= SuperTypeHierarchyCache.getTypeHierarchy(declaringType); return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, declaringType, method.getElementName(), method.getParameterTypes(), method.isConstructor()); } protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) { if (c.offset < 2 || d.getLength() == 0) { return; } try { if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$ // modify document command c.length++; c.offset--; } } catch (BadLocationException excp) { // stop work } } /** * Guesses if the command operates within a newly created javadoc comment or not. * If in doubt, it will assume that the javadoc is new. */ private static boolean isNewComment(IDocument document, int commandOffset) { try { int lineIndex= document.getLineOfOffset(commandOffset) + 1; if (lineIndex >= document.getNumberOfLines()) return true; IRegion line= document.getLineInformation(lineIndex); ITypedRegion partition= document.getPartition(commandOffset); if (document.getLineOffset(lineIndex) >= partition.getOffset() + partition.getLength()) return true; String string= document.get(line.getOffset(), line.getLength()); if (!string.trim().startsWith("*")) //$NON-NLS-1$ return true; return false; } catch (BadLocationException e) { return false; } } /* * @see IAutoIndentStrategy#customizeDocumentCommand */ public void customizeDocumentCommand(IDocument document, DocumentCommand command) { try { if (command.text != null && command.length == 0) { String[] lineDelimiters= document.getLegalLineDelimiters(); int index= TextUtilities.endsWith(lineDelimiters, command.text); if (index > -1) { // ends with line delimiter if (lineDelimiters[index].equals(command.text)) // just the line delimiter jdocIndentAfterNewLine(document, command); return; } } if (command.text != null && command.text.equals("/")) { //$NON-NLS-1$ jdocIndentForCommentEnd(document, command); return; } ITypedRegion partition= document.getPartition(command.offset); int partitionStart= partition.getOffset(); int partitionEnd= partition.getLength() + partitionStart; String text= command.text; int offset= command.offset; int length= command.length; // partition change final int PREFIX_LENGTH= "/*".length(); //$NON-NLS-1$ final int POSTFIX_LENGTH= "*/".length(); //$NON-NLS-1$ if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd - POSTFIX_LENGTH) || text != null && text.length() >= 2 && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$ return; if (command.text == null || command.text.length() == 0) jdocHandleBackspaceDelete(document, command); else if (command.text != null && command.length == 0 && command.text.length() > 0) jdocWrapParagraphOnInsert(document, command); } catch (BadLocationException e) { JavaPlugin.log(e); } } private void flushCommand(IDocument document, DocumentCommand command) throws BadLocationException { if (!command.doit) return; document.replace(command.offset, command.length, command.text); command.doit= false; if (command.text != null) command.offset += command.text.length(); command.length= 0; command.text= null; } protected void jdocWrapParagraphOnInsert(IDocument document, DocumentCommand command) throws BadLocationException { // Assert.isTrue(command.length == 0); // Assert.isTrue(command.text != null && command.text.length() == 1); if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) return; int line= document.getLineOfOffset(command.offset); IRegion region= document.getLineInformation(line); int lineOffset= region.getOffset(); int lineLength= region.getLength(); String lineContents= document.get(lineOffset, lineLength); StringBuffer buffer= new StringBuffer(lineContents); int start= command.offset - lineOffset; int end= command.length + start; buffer.replace(start, end, command.text); // handle whitespace if (command.text != null && command.text.length() != 0 && command.text.trim().length() == 0) { String endOfLine= document.get(command.offset, lineOffset + lineLength - command.offset); // end of line if (endOfLine.length() == 0) { // move caret to next line flushCommand(document, command); if (isLineTooShort(document, line)) { int[] caretOffset= {command.offset}; jdocWrapParagraphFromLine(document, line, caretOffset, false); command.offset= caretOffset[0]; return; } // move caret to next line if possible if (line < document.getNumberOfLines() - 1 && isJavaDocLine(document, line + 1)) { String lineDelimiter= document.getLineDelimiter(line); String nextLinePrefix= jdocExtractLinePrefix(document, line + 1); command.offset += lineDelimiter.length() + nextLinePrefix.length(); } return; // inside whitespace at end of line } else if (endOfLine.trim().length() == 0) { // simply insert space return; } } // change in prefix region String prefix= jdocExtractLinePrefix(document, line); boolean wrapAlways= command.offset >= lineOffset && command.offset <= lineOffset + prefix.length(); // must insert the text now because it may include whitepace flushCommand(document, command); if (wrapAlways || calculateDisplayedWidth(buffer.toString()) > getMargin() || isLineTooShort(document, line)) { int[] caretOffset= {command.offset}; jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways); if (!wrapAlways) command.offset= caretOffset[0]; } } /** * Method jdocWrapParagraphFromLine. * * @param document * @param line * @param always */ private void jdocWrapParagraphFromLine(IDocument document, int line, int[] caretOffset, boolean always) throws BadLocationException { String indent= jdocExtractLinePrefix(document, line); if (!always) { if (!indent.trim().startsWith("*")) //$NON-NLS-1$ return; if (indent.trim().startsWith("*/")) //$NON-NLS-1$ return; if (!isLineTooLong(document, line) && !isLineTooShort(document, line)) return; } boolean caretRelativeToParagraphOffset= false; int caret= caretOffset[0]; int caretLine= document.getLineOfOffset(caret); int lineOffset= document.getLineOffset(line); int paragraphOffset= lineOffset + indent.length(); if (paragraphOffset < caret) { caret -= paragraphOffset; caretRelativeToParagraphOffset= true; } else { caret -= lineOffset; } StringBuffer buffer= new StringBuffer(); int currentLine= line; while (line == currentLine || isJavaDocLine(document, currentLine)) { if (buffer.length() != 0 && !Character.isWhitespace(buffer.charAt(buffer.length() - 1))) { buffer.append(' '); if (currentLine <= caretLine) { // in this case caretRelativeToParagraphOffset is always true ++caret; } } String string= getLineContents(document, currentLine); buffer.append(string); currentLine++; } String paragraph= buffer.toString(); if (paragraph.trim().length() == 0) return; caretOffset[0]= caretRelativeToParagraphOffset ? caret : 0; String delimiter= document.getLineDelimiter(0); String wrapped= formatParagraph(paragraph, caretOffset, indent, delimiter, getMargin()); int beginning= document.getLineOffset(line); int end= document.getLineOffset(currentLine); document.replace(beginning, end - beginning, wrapped.toString()); caretOffset[0]= caretRelativeToParagraphOffset ? caretOffset[0] + beginning : caret + beginning; } /** * Line break iterator to handle whitespaces as first class citizens. */ private static class LineBreakIterator { private final String fString; private final BreakIterator fIterator= BreakIterator.getLineInstance(); private int fStart; private int fEnd; private int fBufferedEnd; public LineBreakIterator(String string) { fString= string; fIterator.setText(string); } public int first() { fBufferedEnd= -1; fStart= fIterator.first(); return fStart; } public int next() { if (fBufferedEnd != -1) { fStart= fEnd; fEnd= fBufferedEnd; fBufferedEnd= -1; return fEnd; } fStart= fEnd; fEnd= fIterator.next(); if (fEnd == BreakIterator.DONE) return fEnd; final String string= fString.substring(fStart, fEnd); // whitespace if (string.trim().length() == 0) return fEnd; final String word= string.trim(); if (word.length() == string.length()) return fEnd; // suspected whitespace fBufferedEnd= fEnd; return fStart + word.length(); } }; /** * Formats a paragraph, using break iterator. * * @param offset an offset within the paragraph, which will be updated with respect to formatting. */ private static String formatParagraph(String paragraph, int[] offset, String prefix, String lineDelimiter, int margin) { LineBreakIterator iterator= new LineBreakIterator(paragraph); StringBuffer paragraphBuffer= new StringBuffer(); StringBuffer lineBuffer= new StringBuffer(); StringBuffer whiteSpaceBuffer= new StringBuffer(); int index= offset[0]; int indexBuffer= -1; // line delimiter could be null if (lineDelimiter == null) lineDelimiter= ""; //$NON-NLS-1$ for (int start= iterator.first(), end= iterator.next(); end != BreakIterator.DONE; start= end, end= iterator.next()) { String word= paragraph.substring(start, end); // word is whitespace if (word.trim().length() == 0) { whiteSpaceBuffer.append(word); // first word of line is always appended } else if (lineBuffer.length() == 0) { lineBuffer.append(prefix); lineBuffer.append(whiteSpaceBuffer.toString()); lineBuffer.append(word); } else { String line= lineBuffer.toString() + whiteSpaceBuffer.toString() + word.toString(); // margin exceeded if (calculateDisplayedWidth(line) > margin) { // flush line buffer and wrap paragraph paragraphBuffer.append(lineBuffer.toString()); paragraphBuffer.append(lineDelimiter); lineBuffer.setLength(0); lineBuffer.append(prefix); lineBuffer.append(word); // flush index buffer if (indexBuffer != -1) { offset[0]= indexBuffer; // correct for caret in whitespace at the end of line if (whiteSpaceBuffer.length() != 0 && index < start && index >= start - whiteSpaceBuffer.length()) offset[0] -= (index - (start - whiteSpaceBuffer.length())); indexBuffer= -1; } whiteSpaceBuffer.setLength(0); // margin not exceeded } else { lineBuffer.append(whiteSpaceBuffer.toString()); lineBuffer.append(word); whiteSpaceBuffer.setLength(0); } } if (index >= start && index < end) { indexBuffer= paragraphBuffer.length() + lineBuffer.length() + (index - start); if (word.trim().length() != 0) indexBuffer -= word.length(); } } // flush line buffer paragraphBuffer.append(lineBuffer.toString()); paragraphBuffer.append(lineDelimiter); // flush index buffer if (indexBuffer != -1) offset[0]= indexBuffer; // last position is not returned by break iterator else if (offset[0] == paragraph.length()) offset[0]= paragraphBuffer.length() - lineDelimiter.length(); return paragraphBuffer.toString(); } private static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /** * Returns the displayed width of a string, taking in account the displayed tab width. * The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string) { final int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); int column= 0; for (int i= 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else column++; return column; } private String jdocExtractLinePrefix(IDocument d, int line) throws BadLocationException { IRegion region= d.getLineInformation(line); int lineOffset= region.getOffset(); int index= findEndOfWhiteSpace(d, lineOffset, lineOffset + d.getLineLength(line)); if (d.getChar(index) == '*') { index++; if (index != lineOffset + region.getLength() &&d.getChar(index) == ' ') index++; } return d.get(lineOffset, index - lineOffset); } private String getLineContents(IDocument d, int line) throws BadLocationException { int offset = d.getLineOffset(line); int length = d.getLineLength(line); String lineDelimiter= d.getLineDelimiter(line); if (lineDelimiter != null) length= length - lineDelimiter.length(); String lineContents = d.get(offset, length); int trim = jdocExtractLinePrefix(d, line).length(); return lineContents.substring(trim); } private static String getLine(IDocument document, int line) throws BadLocationException { IRegion region= document.getLineInformation(line); return document.get(region.getOffset(), region.getLength()); } /** * Returns <code>true</code> if the javadoc line is too short, <code>false</code> otherwise. */ private boolean isLineTooShort(IDocument document, int line) throws BadLocationException { if (!isJavaDocLine(document, line + 1)) return false; String nextLine= getLineContents(document, line + 1); if (nextLine.trim().length() == 0) return false; return true; } /** * Returns <code>true</code> if the line is too long, <code>false</code> otherwise. */ private boolean isLineTooLong(IDocument document, int line) throws BadLocationException { String lineContents= getLine(document, line); return calculateDisplayedWidth(lineContents) > getMargin(); } private static int getMargin() { return getPreferenceStore().getInt(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); } private static final String[] fgInlineTags= { "<b>", "<i>", "<em>", "<strong>", "<code>" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ }; private boolean isInlineTag(String string) { for (int i= 0; i < fgInlineTags.length; i++) if (string.startsWith(fgInlineTags[i])) return true; return false; } /** * returns true if the specified line is part of a paragraph and should be merged with * the previous line. */ private boolean isJavaDocLine(IDocument document, int line) throws BadLocationException { if (document.getNumberOfLines() < line) return false; int offset= document.getLineOffset(line); int length= document.getLineLength(line); int firstChar= findEndOfWhiteSpace(document, offset, offset + length); length -= firstChar - offset; String lineContents= document.get(firstChar, length); String prefix= lineContents.trim(); if (!prefix.startsWith("*") || prefix.startsWith("*/")) //$NON-NLS-1$ //$NON-NLS-2$ return false; lineContents= lineContents.substring(1).trim().toLowerCase(); // preserve empty lines if (lineContents.length() == 0) return false; // preserve @TAGS if (lineContents.startsWith("@")) //$NON-NLS-1$ return false; // preserve HTML tags which are not inline if (lineContents.startsWith("<") && !isInlineTag(lineContents)) //$NON-NLS-1$ return false; return true; } protected void jdocHandleBackspaceDelete(IDocument document, DocumentCommand c) { if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) return; try { String text= document.get(c.offset, c.length); int line= document.getLineOfOffset(c.offset); int lineOffset= document.getLineOffset(line); // erase line delimiter String lineDelimiter= document.getLineDelimiter(line); if (lineDelimiter != null && lineDelimiter.equals(text)) { String prefix= jdocExtractLinePrefix(document, line + 1); // strip prefix if any if (prefix.length() > 0) { int length= document.getLineDelimiter(line).length() + prefix.length(); document.replace(c.offset, length, null); c.doit= false; c.length= 0; return; } // backspace: beginning of a javadoc line } else if (document.getChar(c.offset - 1) == '*' && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset - lineOffset) { lineDelimiter= document.getLineDelimiter(line - 1); String prefix= jdocExtractLinePrefix(document, line); int length= (lineDelimiter != null ? lineDelimiter.length() : 0) + prefix.length(); document.replace(c.offset - length + 1, length, null); c.doit= false; c.offset -= length - 1; c.length= 0; return; } else { document.replace(c.offset, c.length, null); c.doit= false; c.length= 0; } } catch (BadLocationException e) { JavaPlugin.log(e); } try { int line= document.getLineOfOffset(c.offset); int lineOffset= document.getLineOffset(line); String prefix= jdocExtractLinePrefix(document, line); boolean always= c.offset > lineOffset && c.offset <= lineOffset + prefix.length(); int[] caretOffset= {c.offset}; jdocWrapParagraphFromLine(document, document.getLineOfOffset(c.offset), caretOffset, always); c.offset= caretOffset[0]; } catch (BadLocationException e) { JavaPlugin.log(e); } } /** * Returns the compilation unit of the CompilationUnitEditor invoking the AutoIndentStrategy, * might return <code>null</code> on error. */ private static ICompilationUnit getCompilationUnit() { IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) return null; IWorkbenchPage page= window.getActivePage(); if (page == null) return null; IEditorPart editor= page.getActiveEditor(); if (editor == null) return null; IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(editor.getEditorInput()); if (unit == null) return null; return unit; } }
20,157
Bug 20157 junit: exception on 'recreate suite' if file read-only [JUnit]
F3 (everything using the junit wizards) a. create a test class b. create a suite for this class c. add one more test class d. make the test suite class read-only (its compilation unit) e. select that file and choose 'recreate test suite...' f. check both boxes Java Model Exception: Java Model Status [AllTEsts.java is read-only.] at org.eclipse.jdt.internal.core.Openable.save(Openable.java:448) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.updateTestCasesInSuite (UpdateTestSuite.java:181) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.access$1 (UpdateTestSuite.java:149) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite$1.run (UpdateTestSuite.java:195) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) 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.junit.wizards.UpdateTestSuite.run (UpdateTestSuite.java:113) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:210) 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.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Menu.setVisible(Menu.java:920) at org.eclipse.swt.widgets.Control.WM_CONTEXTMENU(Control.java:2818) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Control.WM_RBUTTONUP(Control.java:3707) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.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:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:739) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:248) at org.eclipse.core.launcher.Main.run(Main.java:697) at org.eclipse.core.launcher.Main.main(Main.java:530)
resolved fixed
af6141c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:44:28Z
2002-06-13T14:53:20Z
org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/util/IJUnitStatusConstants.java
20,157
Bug 20157 junit: exception on 'recreate suite' if file read-only [JUnit]
F3 (everything using the junit wizards) a. create a test class b. create a suite for this class c. add one more test class d. make the test suite class read-only (its compilation unit) e. select that file and choose 'recreate test suite...' f. check both boxes Java Model Exception: Java Model Status [AllTEsts.java is read-only.] at org.eclipse.jdt.internal.core.Openable.save(Openable.java:448) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.updateTestCasesInSuite (UpdateTestSuite.java:181) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.access$1 (UpdateTestSuite.java:149) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite$1.run (UpdateTestSuite.java:195) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) 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.junit.wizards.UpdateTestSuite.run (UpdateTestSuite.java:113) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:210) 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.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Menu.setVisible(Menu.java:920) at org.eclipse.swt.widgets.Control.WM_CONTEXTMENU(Control.java:2818) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Control.WM_RBUTTONUP(Control.java:3707) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.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:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:739) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:248) at org.eclipse.core.launcher.Main.run(Main.java:697) at org.eclipse.core.launcher.Main.main(Main.java:530)
resolved fixed
af6141c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:44:28Z
2002-06-13T14:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/util/IJUnitStatusConstants.java
20,157
Bug 20157 junit: exception on 'recreate suite' if file read-only [JUnit]
F3 (everything using the junit wizards) a. create a test class b. create a suite for this class c. add one more test class d. make the test suite class read-only (its compilation unit) e. select that file and choose 'recreate test suite...' f. check both boxes Java Model Exception: Java Model Status [AllTEsts.java is read-only.] at org.eclipse.jdt.internal.core.Openable.save(Openable.java:448) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.updateTestCasesInSuite (UpdateTestSuite.java:181) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.access$1 (UpdateTestSuite.java:149) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite$1.run (UpdateTestSuite.java:195) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) 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.junit.wizards.UpdateTestSuite.run (UpdateTestSuite.java:113) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:210) 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.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Menu.setVisible(Menu.java:920) at org.eclipse.swt.widgets.Control.WM_CONTEXTMENU(Control.java:2818) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Control.WM_RBUTTONUP(Control.java:3707) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.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:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:739) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:248) at org.eclipse.core.launcher.Main.run(Main.java:697) at org.eclipse.core.launcher.Main.main(Main.java:530)
resolved fixed
af6141c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:44:28Z
2002-06-13T14:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/util/JUnitStatus.java
/* * Copyright (c) 2002 IBM Corp. All rights reserved. * This file is made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html */ package org.eclipse.jdt.internal.junit.util; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jface.util.Assert; /** * An implemention of IStatus. * TO DO: Why is it duplicated, it should leverage the Status base class??? */ public class JUnitStatus implements IStatus { private String fStatusMessage; private int fSeverity; /** * Creates a status set to OK (no message) */ public JUnitStatus() { this(OK, null); } /** * Creates a status . * @param severity The status severity: ERROR, WARNING, INFO and OK. * @param message The message of the status. Applies only for ERROR, * WARNING and INFO. */ public JUnitStatus(int severity, String message) { fStatusMessage= message; fSeverity= severity; } /** * Returns if the status' severity is OK. */ public boolean isOK() { return fSeverity == IStatus.OK; } /** * Returns if the status' severity is WARNING. */ public boolean isWarning() { return fSeverity == IStatus.WARNING; } /** * Returns if the status' severity is INFO. */ public boolean isInfo() { return fSeverity == IStatus.INFO; } /** * Returns if the status' severity is ERROR. */ public boolean isError() { return fSeverity == IStatus.ERROR; } /** * @see IStatus#getMessage */ public String getMessage() { return fStatusMessage; } /** * Sets the status to ERROR. * @param The error message (can be empty, but not null) */ public void setError(String errorMessage) { Assert.isNotNull(errorMessage); fStatusMessage= errorMessage; fSeverity= IStatus.ERROR; } /** * Sets the status to WARNING. * @param The warning message (can be empty, but not null) */ public void setWarning(String warningMessage) { Assert.isNotNull(warningMessage); fStatusMessage= warningMessage; fSeverity= IStatus.WARNING; } /** * Sets the status to INFO. * @param The info message (can be empty, but not null) */ public void setInfo(String infoMessage) { Assert.isNotNull(infoMessage); fStatusMessage= infoMessage; fSeverity= IStatus.INFO; } /** * Sets the status to OK. */ public void setOK() { fStatusMessage= null; fSeverity= IStatus.OK; } /* * @see IStatus#matches(int) */ public boolean matches(int severityMask) { return (fSeverity & severityMask) != 0; } /** * Returns always <code>false</code>. * @see IStatus#isMultiStatus() */ public boolean isMultiStatus() { return false; } /* * @see IStatus#getSeverity() */ public int getSeverity() { return fSeverity; } /* * @see IStatus#getPlugin() */ public String getPlugin() { return JUnitPlugin.PLUGIN_ID; } /** * Returns always <code>null</code>. * @see IStatus#getException() */ public Throwable getException() { return null; } /** * Returns always the error severity. * @see IStatus#getCode() */ public int getCode() { return fSeverity; } /** * Returns always <code>null</code>. * @see IStatus#getChildren() */ public IStatus[] getChildren() { return new IStatus[0]; } }
20,157
Bug 20157 junit: exception on 'recreate suite' if file read-only [JUnit]
F3 (everything using the junit wizards) a. create a test class b. create a suite for this class c. add one more test class d. make the test suite class read-only (its compilation unit) e. select that file and choose 'recreate test suite...' f. check both boxes Java Model Exception: Java Model Status [AllTEsts.java is read-only.] at org.eclipse.jdt.internal.core.Openable.save(Openable.java:448) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.updateTestCasesInSuite (UpdateTestSuite.java:181) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.access$1 (UpdateTestSuite.java:149) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite$1.run (UpdateTestSuite.java:195) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) 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.junit.wizards.UpdateTestSuite.run (UpdateTestSuite.java:113) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:210) 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.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Menu.setVisible(Menu.java:920) at org.eclipse.swt.widgets.Control.WM_CONTEXTMENU(Control.java:2818) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Control.WM_RBUTTONUP(Control.java:3707) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.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:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:739) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:248) at org.eclipse.core.launcher.Main.run(Main.java:697) at org.eclipse.core.launcher.Main.main(Main.java:530)
resolved fixed
af6141c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:44:28Z
2002-06-13T14:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/util/Resources.java
20,157
Bug 20157 junit: exception on 'recreate suite' if file read-only [JUnit]
F3 (everything using the junit wizards) a. create a test class b. create a suite for this class c. add one more test class d. make the test suite class read-only (its compilation unit) e. select that file and choose 'recreate test suite...' f. check both boxes Java Model Exception: Java Model Status [AllTEsts.java is read-only.] at org.eclipse.jdt.internal.core.Openable.save(Openable.java:448) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.updateTestCasesInSuite (UpdateTestSuite.java:181) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.access$1 (UpdateTestSuite.java:149) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite$1.run (UpdateTestSuite.java:195) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) 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.junit.wizards.UpdateTestSuite.run (UpdateTestSuite.java:113) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:210) 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.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Menu.setVisible(Menu.java:920) at org.eclipse.swt.widgets.Control.WM_CONTEXTMENU(Control.java:2818) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Control.WM_RBUTTONUP(Control.java:3707) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.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:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:739) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:248) at org.eclipse.core.launcher.Main.run(Main.java:697) at org.eclipse.core.launcher.Main.main(Main.java:530)
resolved fixed
af6141c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:44:28Z
2002-06-13T14:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestSuiteCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.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.junit.ui.IJUnitHelpContextIds; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.ExceptionHandler; 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.SWTUtil; 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.IDialogSettings; 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; import org.eclipse.ui.help.WorkbenchHelp; /** * 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$ 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$ public static final String START_MARKER= "//$JUnit-BEGIN$"; //$NON-NLS-1$ public static final String END_MARKER= "//$JUnit-END$"; //$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 MethodStubsSelectionButtonGroup fMethodStubsButtons; private boolean fUpdatedExistingClassButton; protected IStatus fClassesInSuiteStatus; protected IStatus fSuiteNameStatus; public NewTestSuiteCreationWizardPage() { super(true, PAGE_NAME); fSuiteNameStatus= new JUnitStatus(); fSuiteNameTextInitialValue= ""; //$NON-NLS-1$ setTitle(WizardMessages.getString("NewTestSuiteWizPage.title")); //$NON-NLS-1$ setDescription(WizardMessages.getString("NewTestSuiteWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ }; fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage2.method.Stub.label")); //$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); createMethodStubSelectionControls(composite, nColumns); setControl(composite); restoreWidgetValues(); WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTSUITE_WIZARD_PAGE); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } /** * Should be called from the wizard with the initial selection. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); doStatusUpdate(); fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text } /** * @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(); fSuiteNameStatus= testSuiteChanged(); //must check this one too 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 most severe status will be displayed and the ok button enabled/disabled. updateStatus(status); } /** * @see DialogPage#setVisible(boolean) */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { setFocus(); updateClassesInSuiteTable(); handleAllFieldsChanged(); } } private void handleAllFieldsChanged() { handleFieldChanged(PACKAGE); handleFieldChanged(CONTAINER); handleFieldChanged(CLASSES_IN_SUITE); handleFieldChanged(SUITE_NAME); } 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(WizardMessages.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= 80; 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(WizardMessages.getString("NewTestSuiteWizPage.selectAll")); //$NON-NLS-1$ GridData bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); bgd.heightHint = SWTUtil.getButtonHeigthHint(fSelectAllButton); bgd.widthHint = SWTUtil.getButtonWidthHint(fSelectAllButton); 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(WizardMessages.getString("NewTestSuiteWizPage.deselectAll")); //$NON-NLS-1$ bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); bgd.heightHint = SWTUtil.getButtonHeigthHint(fDeselectAllButton); bgd.widthHint = SWTUtil.getButtonWidthHint(fDeselectAllButton); 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 { public ClassesInSuitContentProvider() { super(); } public Object[] getElements(Object parent) { try { if (parent instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) parent; if (pack.exists()) { 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, ImportsManager imports, IProgressMonitor monitor) throws CoreException { writeImports(imports); if (fMethodStubsButtons.isEnabled() && fMethodStubsButtons.isSelected(0)) createMain(type); type.createMethod(getSuiteMethodString(), null, false, null); } protected void createMain(IType type) throws JavaModelException { type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null); } /** * Returns the string content for creating a new suite() method. */ 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(); } /** * Returns the new code to be included in a new suite() or which replaces old code in an existing suite(). */ public static String getUpdatableString(Object[] selectedClasses) throws JavaModelException { StringBuffer suite= new StringBuffer(); suite.append(START_MARKER+"\n"); //$NON-NLS-1$ for (int i= 0; i < selectedClasses.length; i++) { if (selectedClasses[i] instanceof IType) { IType testType= (IType) selectedClasses[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"+END_MARKER); //$NON-NLS-1$ return suite.toString(); } private String getUpdatableString() throws JavaModelException { return getUpdatableString(fClassesInSuiteTable.getCheckedElements()); } /** * Runnable for replacing an existing suite() method. */ 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(WizardMessages.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(START_MARKER) --> int start= source.indexOf(START_MARKER); int start= source.toString().indexOf(START_MARKER); if (start > -1) { //using JDK 1.4 //int end= source.toString().indexOf(END_MARKER, start) --> int end= source.indexOf(END_MARKER, start) int end= source.toString().indexOf(END_MARKER, start); if (end > -1) { monitor.subTask(WizardMessages.getString("NewTestSuiteWizPage.createType.updating.suite_method")); //$NON-NLS-1$ monitor.worked(1); end += END_MARKER.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(), WizardMessages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.title"), WizardMessages.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) { String title= WizardMessages.getString("NewTestSuiteWizPage.error_tile"); //$NON-NLS-1$ String message= WizardMessages.getString("NewTestSuiteWizPage.error_message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } } /** * Returns true iff an existing suite() method has been replaced. */ public boolean hasUpdatedExistingClass() { return fUpdatedExistingClassButton; } private IStatus classesInSuiteChanged() { JUnitStatus status= new JUnitStatus(); if (fClassesInSuiteTable.getCheckedElements().length <= 0) status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.classes_in_suite.error.no_testclasses_selected")); //$NON-NLS-1$ return status; } private void updateSelectedClassesLabel() { int noOfClassesChecked= fClassesInSuiteTable.getCheckedElements().length; String key= (noOfClassesChecked==1) ? "NewTestClassWizPage.treeCaption.classSelected" : "NewTestClassWizPage.treeCaption.classesSelected"; //$NON-NLS-1$ //$NON-NLS-2$ fSelectedClassesLabel.setText(WizardMessages.getFormattedString(key, new Integer(noOfClassesChecked))); } protected void createSuiteNameControl(Composite composite, int nColumns) { fSuiteNameLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fSuiteNameLabel.setFont(composite.getFont()); fSuiteNameLabel.setText(WizardMessages.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= GridData.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(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } JUnitStatus recursiveSuiteInclusionStatus= checkRecursiveTestSuiteInclusion(); if (! recursiveSuiteInclusionStatus.isOK()) return recursiveSuiteInclusionStatus; IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.typeName.warning.already_exists")); //$NON-NLS-1$ fMethodStubsButtons.setEnabled(false); return status; } } fMethodStubsButtons.setEnabled(true); return status; } private JUnitStatus checkRecursiveTestSuiteInclusion(){ if (fClassesInSuiteTable == null) return new JUnitStatus(); String typeName= getTypeName(); JUnitStatus status= new JUnitStatus(); Object[] checkedClasses= fClassesInSuiteTable.getCheckedElements(); for (int i= 0; i < checkedClasses.length; i++) { IType checkedClass= (IType)checkedClasses[i]; if (checkedClass.getElementName().equals(typeName)){ status.setWarning(WizardMessages.getString("NewTestSuiteCreationWizardPage.infinite_recursion")); //$NON-NLS-1$ return status; } } return new JUnitStatus(); } /** * Sets the focus. */ protected void setFocus() { fSuiteNameText.setFocus(); } /** * Sets the classes in <code>elements</code> as checked. */ public void setCheckedElements(Object[] elements) { fClassesInSuiteTable.setCheckedElements(elements); } protected void cannotUpdateSuiteError() { MessageDialog.openError(getShell(), WizardMessages.getString("NewTestSuiteWizPage.cannotUpdateDialog.title"), //$NON-NLS-1$ WizardMessages.getFormattedString("NewTestSuiteWizPage.cannotUpdateDialog.message", new String[] {START_MARKER, END_MARKER})); //$NON-NLS-1$ } private void writeImports(ImportsManager imports) { imports.addImport("junit.framework.Test"); //$NON-NLS-1$ imports.addImport("junit.framework.TestSuite"); //$NON-NLS-1$ } /** * 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)); //The next 2 lines are necessary. Otherwise, if fMethodsStubsButtons is disabled, and USE_TESTRUNNER gets enabled, //then the checkbox for USE_TESTRUNNER will be the only enabled component of fMethodsStubsButton fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled()); fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled()); 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()); } } }
20,157
Bug 20157 junit: exception on 'recreate suite' if file read-only [JUnit]
F3 (everything using the junit wizards) a. create a test class b. create a suite for this class c. add one more test class d. make the test suite class read-only (its compilation unit) e. select that file and choose 'recreate test suite...' f. check both boxes Java Model Exception: Java Model Status [AllTEsts.java is read-only.] at org.eclipse.jdt.internal.core.Openable.save(Openable.java:448) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.updateTestCasesInSuite (UpdateTestSuite.java:181) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite.access$1 (UpdateTestSuite.java:149) at org.eclipse.jdt.internal.junit.wizards.UpdateTestSuite$1.run (UpdateTestSuite.java:195) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) 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.junit.wizards.UpdateTestSuite.run (UpdateTestSuite.java:113) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:210) 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.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Menu.setVisible(Menu.java:920) at org.eclipse.swt.widgets.Control.WM_CONTEXTMENU(Control.java:2818) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java(Compiled Code)) at org.eclipse.swt.widgets.Control.WM_RBUTTONUP(Control.java:3707) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.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:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:739) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:248) at org.eclipse.core.launcher.Main.run(Main.java:697) at org.eclipse.core.launcher.Main.main(Main.java:530)
resolved fixed
af6141c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T16:44:28Z
2002-06-13T14:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/UpdateTestSuite.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.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.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.*; 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; import org.eclipse.ui.dialogs.ISelectionStatusValidator; /** * 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 ISelectionStatusValidator { /* * @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= WizardMessages.getFormattedString("UpdateAllTests.selected_methods.label_one", new Integer(count)); //$NON-NLS-1$ } else { message= WizardMessages.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= fTestSuite.findPrimaryType(); 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.START_MARKER); if (start > -1) { if (originalContent.indexOf(NewTestSuiteCreationWizardPage.END_MARKER, start) > -1) { CheckedTableSelectionDialog dialog= new CheckedTableSelectionDialog(fShell, lprovider, cprovider); dialog.setValidator(new UpdateAllTestsValidator()); dialog.setTitle(WizardMessages.getString("UpdateAllTests.title")); //$NON-NLS-1$ dialog.setMessage(WizardMessages.getString("UpdateAllTests.message")); //$NON-NLS-1$ dialog.setInitialSelections(cprovider.getElements(fPack)); dialog.setSize(60, 25); dialog.setInput(fPack); if (dialog.open() == CheckedTableSelectionDialog.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(WizardMessages.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.START_MARKER); 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.END_MARKER, start); if (end > -1) { monitor.worked(1); end += NewTestSuiteCreationWizardPage.END_MARKER.length(); // String updatableCode= source.substring(start,end+NewTestSuiteCreationWizardPage.endMarker.length()); source.replace(start, end, NewTestSuiteCreationWizardPage.getUpdatableString(fSelectedTestCases)); 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) { 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); } }; } private void cannotUpdateSuiteError() { MessageDialog.openError(fShell, WizardMessages.getString("UpdateAllTests.cannotUpdate.errorDialog.title"), //$NON-NLS-1$ WizardMessages.getFormattedString("UpdateAllTests.cannotUpdate.errorDialog.message", new String[] {NewTestSuiteCreationWizardPage.START_MARKER, NewTestSuiteCreationWizardPage.END_MARKER})); //$NON-NLS-1$ } private void noSuiteError() { MessageDialog.openError(fShell, WizardMessages.getString("UpdateAllTests.cannotFind.errorDialog.title"), WizardMessages.getString("UpdateAllTests.cannotFind.errorDialog.message")); //$NON-NLS-1$ //$NON-NLS-2$ } }
30,380
Bug 30380 Show outline doesn't get focus
I2003-01-22 Assuming this is an SWT issue. Using the newly "Show Outline" feature brings up the outline popup. However, on MacOS X, the input area doesn't have the focus, so performing some keyboard input results in changes to the editor instead ....
verified fixed
b14299f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T17:53:35Z
2003-01-28T13:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaOutlineInformationControl.java
/* * Copyright (c) 2000, 2002 IBM Corp. and others.. * All rights reserved. ? This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html ?* * Contributors: * IBM Corporation - initial API and implementation */ package org.eclipse.jdt.internal.ui.text; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlExtension; import org.eclipse.jface.text.IInformationControlExtension2; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.OpenActionUtil; import org.eclipse.jdt.internal.ui.util.StringMatcher; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; /** * @author dmegert * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class JavaOutlineInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2 { /** * The NamePatternFilter selects the elements which * match the given string patterns. * <p> * The following characters have special meaning: * ? => any character * * => any string * </p> * * @since 2.0 */ private static class NamePatternFilter extends ViewerFilter { private String fPattern; private StringMatcher fMatcher; private ILabelProvider fLabelProvider; private Viewer fViewer; private StringMatcher getMatcher() { return fMatcher; } /* (non-Javadoc) * Method declared on ViewerFilter. */ public boolean select(Viewer viewer, Object parentElement, Object element) { if (fMatcher == null) return true; ILabelProvider labelProvider= getLabelProvider(viewer); String matchName= null; if (labelProvider != null) matchName= ((ILabelProvider)labelProvider).getText(element); else if (element instanceof IJavaElement) matchName= ((IJavaElement) element).getElementName(); if (matchName != null && fMatcher.match(matchName)) return true; return hasUnfilteredChild(viewer, element); } private ILabelProvider getLabelProvider(Viewer viewer) { if (fViewer == viewer) return fLabelProvider; fLabelProvider= null; IBaseLabelProvider baseLabelProvider= null; if (viewer instanceof StructuredViewer) baseLabelProvider= ((StructuredViewer)viewer).getLabelProvider(); if (baseLabelProvider instanceof ILabelProvider) fLabelProvider= (ILabelProvider)baseLabelProvider; return fLabelProvider; } private boolean hasUnfilteredChild(Viewer viewer, Object element) { IJavaElement[] children; if (element instanceof IParent) { try { children= ((IParent)element).getChildren(); } catch (JavaModelException ex) { return false; } for (int i= 0; i < children.length; i++) if (select(viewer, element, children[i])) return true; } return false; } /** * Sets the patterns to filter out for the receiver. * <p> * The following characters have special meaning: * ? => any character * * => any string * </p> */ public void setPattern(String pattern) { fPattern= pattern; if (fPattern == null) { fMatcher= null; return; } boolean ignoreCase= pattern.toLowerCase().equals(pattern); fMatcher= new StringMatcher(pattern, ignoreCase, false); } } private static class BorderFillLayout extends Layout { /** The border widths. */ final int fBorderSize; /** * Creates a fill layout with a border. */ public BorderFillLayout(int borderSize) { if (borderSize < 0) throw new IllegalArgumentException(); fBorderSize= borderSize; } /** * Returns the border size. */ public int getBorderSize() { return fBorderSize; } /* * @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite, int, int, boolean) */ protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { Control[] children= composite.getChildren(); Point minSize= new Point(0, 0); if (children != null) { for (int i= 0; i < children.length; i++) { Point size= children[i].computeSize(wHint, hHint, flushCache); minSize.x= Math.max(minSize.x, size.x); minSize.y= Math.max(minSize.y, size.y); } } minSize.x += fBorderSize * 2 + RIGHT_MARGIN; minSize.y += fBorderSize * 2; return minSize; } /* * @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite, boolean) */ protected void layout(Composite composite, boolean flushCache) { Control[] children= composite.getChildren(); Point minSize= new Point(composite.getClientArea().width, composite.getClientArea().height); if (children != null) { for (int i= 0; i < children.length; i++) { Control child= children[i]; child.setSize(minSize.x - fBorderSize * 2, minSize.y - fBorderSize * 2); child.setLocation(fBorderSize, fBorderSize); } } } } /** Border thickness in pixels. */ private static final int BORDER= 1; /** Right margin in pixels. */ private static final int RIGHT_MARGIN= 3; /** The control's shell */ private Shell fShell; /** The composite */ Composite fComposite; /** The control's text widget */ private Text fFilterText; /** The control's tree widget */ private TreeViewer fTreeViewer; /** The control width constraint */ private int fMaxWidth= -1; /** The control height constraint */ private int fMaxHeight= -1; private StringMatcher fStringMatcher; /** * Creates a tree information control with the given shell as parent. The given * style is applied to the tree widget. * * @param parent the parent shell * @param style the additional styles for the tree widget */ public JavaOutlineInformationControl(Shell parent, int style) { this(parent, SWT.NO_TRIM, style); } /** * Creates a tree information control with the given shell as parent. * No additional styles are applied. * * @param parent the parent shell */ public JavaOutlineInformationControl(Shell parent) { this(parent, SWT.NONE); } /** * Creates a tree information control with the given shell as parent. The given * styles are applied to the shell and the tree widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param treeStyle the additional styles for the tree widget */ public JavaOutlineInformationControl(Shell parent, int shellStyle, int treeStyle) { fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); Display display= fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); // Composite for filter text and tree fComposite= new Composite(fShell,SWT.RESIZE); GridLayout layout= new GridLayout(1, false); fComposite.setLayout(layout); fComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); createFilterText(fComposite); createTreeViewer(fComposite, treeStyle); int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; fShell.setLayout(new BorderFillLayout(border)); setInfoSystemColor(); installFilter(); } private void createTreeViewer(Composite parent, int style) { Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI)); GridData data= new GridData(GridData.FILL_BOTH); tree.setLayoutData(data); fTreeViewer= new TreeViewer(tree); // Hide import declartions but show the container fTreeViewer.addFilter(new ViewerFilter() { public boolean select(Viewer viewer, Object parentElement, Object element) { return !(element instanceof IImportDeclaration); } }); fTreeViewer.setContentProvider(new StandardJavaElementContentProvider(true, true)); fTreeViewer.setSorter(new JavaElementSorter()); fTreeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS ); fTreeViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); fTreeViewer.getTree().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC dispose(); } public void keyReleased(KeyEvent e) { // do nothing } }); fTreeViewer.getTree().addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { // do nothing } public void widgetDefaultSelected(SelectionEvent e) { gotoSelectedElement(); } }); } private Text createFilterText(Composite parent) { fFilterText= new Text(parent, SWT.FLAT); GridData data= new GridData(); GC gc= new GC(parent); gc.setFont(parent.getFont()); FontMetrics fontMetrics= gc.getFontMetrics(); gc.dispose(); data.heightHint= org.eclipse.jface.dialogs.Dialog.convertHeightInCharsToPixels(fontMetrics, 1); data.horizontalAlignment= GridData.FILL; data.verticalAlignment= GridData.BEGINNING; fFilterText.setLayoutData(data); fFilterText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.keyCode == 0x0D) // return gotoSelectedElement(); if (e.keyCode == SWT.ARROW_DOWN) fTreeViewer.getTree().setFocus(); if (e.keyCode == SWT.ARROW_UP) fTreeViewer.getTree().setFocus(); } public void keyReleased(KeyEvent e) { // do nothing } }); // Horizonral separator line Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return fFilterText; } private void setInfoSystemColor() { Display display= fShell.getDisplay(); setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } private void installFilter() { final NamePatternFilter viewerFilter= new NamePatternFilter(); fTreeViewer.addFilter(viewerFilter); fFilterText.setText(""); //$NON-NLS-1$ fFilterText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String pattern= fFilterText.getText(); if (pattern != null) { int length= pattern.length(); if (length == 0) pattern= null; else if (pattern.charAt(length -1 ) != '*') pattern= pattern + '*'; } else pattern= null; viewerFilter.setPattern(pattern); fStringMatcher= viewerFilter.getMatcher(); fTreeViewer.getControl().setRedraw(false); fTreeViewer.refresh(); fTreeViewer.expandAll(); selectFirstMatch(); fTreeViewer.getControl().setRedraw(true); } }); } private void gotoSelectedElement() { Object selectedElement= ((IStructuredSelection)fTreeViewer.getSelection()).getFirstElement(); if (selectedElement != null) { try { dispose(); OpenActionUtil.open(selectedElement, true); } catch (CoreException ex) { JavaPlugin.log(ex); } } } /** * Selects the first element in the tree which * matches the current filter pattern. */ private void selectFirstMatch() { Tree tree= fTreeViewer.getTree(); Object element= findElement(tree.getItems()); if (element != null) fTreeViewer.setSelection(new StructuredSelection(element), true); else fTreeViewer.setSelection(StructuredSelection.EMPTY); } private IJavaElement findElement(TreeItem[] items) { ILabelProvider labelProvider= (ILabelProvider)fTreeViewer.getLabelProvider(); for (int i= 0; i < items.length; i++) { IJavaElement element= (IJavaElement)items[i].getData(); if (fStringMatcher == null) return element; if (element != null) { String label= labelProvider.getText(element); if (fStringMatcher.match(label)) return element; } element= findElement(items[i].getItems()); if (element != null) return element; } return null; } /* * @see IInformationControl#setInformation(String) */ public void setInformation(String information) { // this method is ignored, see IInformationControlExtension2 } /* * @see IInformationControlExtension2#setInput(Object) */ public void setInput(Object information) { fFilterText.setText(""); //$NON-NLS-1$ if (information == null || information instanceof String) { setInput(null); return; } IJavaElement je= (IJavaElement)information; IJavaElement sel= null; ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) sel= cu; else sel= je.getAncestor(IJavaElement.CLASS_FILE); fTreeViewer.setInput(sel); fTreeViewer.setSelection(new StructuredSelection(information)); } /* * @see IInformationControl#setVisible(boolean) */ public void setVisible(boolean visible) { fShell.setVisible(visible); } /* * @see IInformationControl#dispose() */ public void dispose() { if (fShell != null) { if (!fShell.isDisposed()) fShell.dispose(); fShell= null; fTreeViewer= null; fComposite= null; fFilterText= null; } } /* * @see org.eclipse.jface.text.IInformationControlExtension#hasContents() */ public boolean hasContents() { return fTreeViewer != null && fTreeViewer.getInput() != null; } /* * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { fMaxWidth= maxWidth; fMaxHeight= maxHeight; } /* * @see org.eclipse.jface.text.IInformationControl#computeSizeHint() */ public Point computeSizeHint() { return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); } /* * @see IInformationControl#setLocation(Point) */ public void setLocation(Point location) { Rectangle trim= fShell.computeTrim(0, 0, 0, 0); Point textLocation= fComposite.getLocation(); location.x += trim.x - textLocation.x; location.y += trim.y - textLocation.y; fShell.setLocation(location); } /* * @see IInformationControl#setSize(int, int) */ public void setSize(int width, int height) { fShell.setSize(width, height); } /* * @see IInformationControl#addDisposeListener(DisposeListener) */ public void addDisposeListener(DisposeListener listener) { fShell.addDisposeListener(listener); } /* * @see IInformationControl#removeDisposeListener(DisposeListener) */ public void removeDisposeListener(DisposeListener listener) { fShell.removeDisposeListener(listener); } /* * @see IInformationControl#setForegroundColor(Color) */ public void setForegroundColor(Color foreground) { fTreeViewer.getTree().setForeground(foreground); fFilterText.setForeground(foreground); fComposite.setForeground(foreground); } /* * @see IInformationControl#setBackgroundColor(Color) */ public void setBackgroundColor(Color background) { fTreeViewer.getTree().setBackground(background); fFilterText.setBackground(background); fComposite.setBackground(background); } /* * @see IInformationControl#isFocusControl() */ public boolean isFocusControl() { return fShell.isFocusControl(); } /* * @see IInformationControl#setFocus() */ public void setFocus() { fShell.forceFocus(); fFilterText.setFocus(); } /* * @see IInformationControl#addFocusListener(FocusListener) */ public void addFocusListener(FocusListener listener) { fShell.addFocusListener(listener); } /* * @see IInformationControl#removeFocusListener(FocusListener) */ public void removeFocusListener(FocusListener listener) { fShell.removeFocusListener(listener); } }
18,588
Bug 18588 [Workbench] Hierarchy - no progress monitor ?
Build 20020601 Open type java.lang.Object, select Object type name in editor, and hit F4. No progress is shown during hierarchy opening.
resolved wontfix
3937701
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T18:40:40Z
2002-06-01T14:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyLifeCycle.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IRegion; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.ITypeHierarchyChangedListener; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Manages a type hierarchy, to keep it refreshed, and to allow it to be shared. */ public class TypeHierarchyLifeCycle implements ITypeHierarchyChangedListener, IElementChangedListener { private boolean fHierarchyRefreshNeeded; private ITypeHierarchy fHierarchy; private IJavaElement fInputElement; private boolean fIsSuperTypesOnly; private boolean fReconciled; private List fChangeListeners; public TypeHierarchyLifeCycle() { this(false); } public TypeHierarchyLifeCycle(boolean isSuperTypesOnly) { fHierarchy= null; fInputElement= null; fIsSuperTypesOnly= isSuperTypesOnly; fChangeListeners= new ArrayList(2); fReconciled= false; } public ITypeHierarchy getHierarchy() { return fHierarchy; } public IJavaElement getInputElement() { return fInputElement; } public void freeHierarchy() { if (fHierarchy != null) { fHierarchy.removeTypeHierarchyChangedListener(this); JavaCore.removeElementChangedListener(this); fHierarchy= null; fInputElement= null; } } public void removeChangedListener(ITypeHierarchyLifeCycleListener listener) { fChangeListeners.remove(listener); } public void addChangedListener(ITypeHierarchyLifeCycleListener listener) { if (!fChangeListeners.contains(listener)) { fChangeListeners.add(listener); } } private void fireChange(IType[] changedTypes) { for (int i= fChangeListeners.size()-1; i>=0; i--) { ITypeHierarchyLifeCycleListener curr= (ITypeHierarchyLifeCycleListener) fChangeListeners.get(i); curr.typeHierarchyChanged(this, changedTypes); } } public void ensureRefreshedTypeHierarchy(final IJavaElement element, IRunnableContext context) throws JavaModelException { if (element == null || !element.exists()) { freeHierarchy(); return; } boolean hierachyCreationNeeded= (fHierarchy == null || !element.equals(fInputElement)); if (hierachyCreationNeeded || fHierarchyRefreshNeeded) { IRunnableWithProgress op= new IRunnableWithProgress() { public void run(IProgressMonitor pm) throws InvocationTargetException { try { doHierarchyRefresh(element, pm); } catch (JavaModelException e) { throw new InvocationTargetException(e); } } }; try { context.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 if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { IPackageFragmentRoot[] roots= element.getJavaProject().getPackageFragmentRoots(); String name= element.getElementName(); for (int i= 0; i < roots.length; i++) { IPackageFragment pack= roots[i].getPackageFragment(name); if (pack.exists()) { region.add(pack); } } } else { region.add(element); } IJavaProject jproject= element.getJavaProject(); fHierarchy= jproject.newTypeHierarchy(region, pm); } } else { fHierarchy.refresh(pm); } fHierarchy.addTypeHierarchyChangedListener(this); JavaCore.addElementChangedListener(this); } /* * @see ITypeHierarchyChangedListener#typeHierarchyChanged */ public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) { fHierarchyRefreshNeeded= true; } /* * @see IElementChangedListener#elementChanged(ElementChangedEvent) */ public void elementChanged(ElementChangedEvent event) { if (fChangeListeners.isEmpty()) { return; } IJavaElement elem= event.getDelta().getElement(); if (!isReconciled() && elem instanceof IWorkingCopy && ((IWorkingCopy)elem).isWorkingCopy()) { return; } if (fHierarchyRefreshNeeded) { fireChange(null); } else { ArrayList changedTypes= new ArrayList(); processDelta(event.getDelta(), changedTypes); if (changedTypes.size() > 0) { fireChange((IType[]) changedTypes.toArray(new IType[changedTypes.size()])); } } } /* * Assume that the hierarchy is intact (no refresh needed) */ private void processDelta(IJavaElementDelta delta, ArrayList changedTypes) { IJavaElement element= delta.getElement(); switch (element.getElementType()) { case IJavaElement.TYPE: processTypeDelta((IType) element, changedTypes); processChildrenDelta(delta, changedTypes); // (inner types) break; case IJavaElement.JAVA_MODEL: case IJavaElement.JAVA_PROJECT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: processChildrenDelta(delta, changedTypes); break; case IJavaElement.COMPILATION_UNIT: ICompilationUnit cu= (ICompilationUnit)element; boolean isWorkingCopyRemove= isWorkingCopyRemove(cu, delta.getKind()); if (isWorkingCopyRemove || delta.getKind() == IJavaElementDelta.CHANGED && isPossibleStructuralChange(delta.getFlags())) { try { if (isWorkingCopyRemove) cu= (ICompilationUnit)cu.getOriginalElement(); if (cu.exists()) { IType[] types= cu.getAllTypes(); for (int i= 0; i < types.length; i++) { processTypeDelta(types[i], changedTypes); } } } catch (JavaModelException e) { JavaPlugin.log(e); } } else { processChildrenDelta(delta, changedTypes); } break; case IJavaElement.CLASS_FILE: if (delta.getKind() == IJavaElementDelta.CHANGED) { try { IType type= ((IClassFile) element).getType(); processTypeDelta(type, changedTypes); } catch (JavaModelException e) { JavaPlugin.log(e); } } else { processChildrenDelta(delta, changedTypes); } break; } } private boolean isPossibleStructuralChange(int flags) { return (flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT; } private boolean isWorkingCopyRemove(ICompilationUnit cu, int deltaKind) { return isReconciled() && deltaKind == IJavaElementDelta.REMOVED && cu.isWorkingCopy(); } private void processTypeDelta(IType type, ArrayList changedTypes) { type= (IType) JavaModelUtil.toOriginal(type); if (getHierarchy().contains(type)) { changedTypes.add(type); } } private void processChildrenDelta(IJavaElementDelta delta, ArrayList changedTypes) { IJavaElementDelta[] children= delta.getAffectedChildren(); for (int i= 0; i < children.length; i++) { processDelta(children[i], changedTypes); // recursive } } public boolean isReconciled() { return fReconciled; } public void setReconciled(boolean reconciled) { fReconciled= reconciled; } }
18,588
Bug 18588 [Workbench] Hierarchy - no progress monitor ?
Build 20020601 Open type java.lang.Object, select Object type name in editor, and hit F4. No progress is shown during hierarchy opening.
resolved wontfix
3937701
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T18:40:40Z
2002-06-01T14:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectAllAction; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of input elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private IDialogSettings fDialogSettings; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private IPropertyChangeListener fPropertyChangeListener; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private IPartListener2 fPartListener; private int fCurrentOrientation; private boolean fLinkingEnabled; private boolean fIsVisible; private boolean fNeedRefresh; private boolean fIsEnableMemberFilter; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private MethodsViewer fMethodsViewer; private SashForm fTypeMethodsSplitter; private PageBook fViewerbook; private PageBook fPagebook; private Label fNoHierarchyShownLabel; private Label fEmptyTypesViewer; private ViewForm fTypeViewerViewForm; private ViewForm fMethodViewerViewForm; private CLabel fMethodViewerPaneLabel; private JavaUILabelProvider fPaneLabelProvider; private ToggleViewAction[] fViewActions; private ToggleLinkingAction fToggleLinkingAction; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private EnableMemberFilterAction fEnableMemberFilterAction; private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; private SelectAllAction fSelectAllAction; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS)); fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fHierarchyLifeCycle.setReconciled(isReconciled); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fPropertyChangeListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doPropertyChange(event); } }; PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); fIsEnableMemberFilter= false; fInputHistory= new ArrayList(); fAllViewers= null; fViewActions= new ToggleViewAction[] { new ToggleViewAction(this, VIEW_ID_TYPE), new ToggleViewAction(this, VIEW_ID_SUPER), new ToggleViewAction(this, VIEW_ID_SUB) }; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); fHistoryDropDownAction= new HistoryDropDownAction(this); fHistoryDropDownAction.setEnabled(false); fToggleOrientationActions= new ToggleOrientationAction[] { new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE) }; fEnableMemberFilterAction= new EnableMemberFilterAction(this, false); fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener2() { public void partVisible(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part == TypeHierarchyViewPart.this) { visibilityChanged(true); } } public void partHidden(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part == TypeHierarchyViewPart.this) { visibilityChanged(false); } } public void partActivated(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partInputChanged(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part instanceof IEditorPart) editorActivated((IEditorPart) part); }; public void partBroughtToTop(IWorkbenchPartReference ref) {} public void partClosed(IWorkbenchPartReference ref) {} public void partDeactivated(IWorkbenchPartReference ref) {} public void partOpened(IWorkbenchPartReference ref) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR); } /** * Method doPropertyChange. * @param event */ protected void doPropertyChange(PropertyChangeEvent event) { if (fMethodsViewer != null) { if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { fMethodsViewer.refresh(); } } } /** * Adds the entry if new. Inserted at the beginning of the history entries list. */ private void addHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { fInputHistory.remove(entry); } fInputHistory.add(0, entry); fHistoryDropDownAction.setEnabled(true); } private void updateHistoryEntries() { for (int i= fInputHistory.size() - 1; i >= 0; i--) { IJavaElement type= (IJavaElement) fInputHistory.get(i); if (!type.exists()) { fInputHistory.remove(i); } } fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty()); } /** * Goes to the selected entry, without updating the order of history entries. */ public void gotoHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { updateInput(entry); } } /** * Gets all history entries. */ public IJavaElement[] getHistoryEntries() { if (fInputHistory.size() > 0) { updateHistoryEntries(); } return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]); } /** * Sets the history entries */ public void setHistoryEntries(IJavaElement[] elems) { fInputHistory.clear(); for (int i= 0; i < elems.length; i++) { fInputHistory.add(elems[i]); } updateHistoryEntries(); } /** * Selects an member in the methods list or in the current hierarchy. */ public void selectMember(IMember member) { if (member.getElementType() != IJavaElement.TYPE) { // methods are working copies if (fHierarchyLifeCycle.isReconciled()) { member= JavaModelUtil.toWorkingCopy(member); } Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { methodControl.setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } else { Control viewerControl= getCurrentViewer().getControl(); if (viewerControl != null && !viewerControl.isDisposed()) { viewerControl.setFocus(); } // types are originals member= JavaModelUtil.toOriginal(member); if (!member.equals(fSelectedType)) { getCurrentViewer().setSelection(new StructuredSelection(member), true); } } } /** * @deprecated */ public IType getInput() { if (fInputElement instanceof IType) { return (IType) fInputElement; } return null; } /** * Sets the input to a new type * @deprecated */ public void setInput(IType type) { setInputElement(type); } /** * Returns the input element of the type hierarchy. * Can be of type <code>IType</code> or <code>IPackageFragment</code> */ public IJavaElement getInputElement() { return fInputElement; } /** * Sets the input to a new element. */ public void setInputElement(IJavaElement element) { if (element != null) { if (element instanceof IMember) { if (element.getElementType() != IJavaElement.TYPE) { element= ((IMember) element).getDeclaringType(); } ICompilationUnit cu= ((IMember) element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { element= cu.getOriginal(element); if (!element.exists()) { MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ return; } } } else { int kind= element.getElementType(); if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) { element= null; JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$ } } } if (element != null && !element.equals(fInputElement)) { addHistoryEntry(element); } updateInput(element); } /** * Changes the input to a new type */ private void updateInput(IJavaElement inputElement) { IJavaElement prevInput= fInputElement; // Make sure the UI got repainted before we execute a long running // operation. This can be removed if we refresh the hierarchy in a // separate thread. // Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881 processOutstandingEvents(); fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e); clearInput(); return; } if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(true); } IType root= getSelectableType(fInputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); fPagebook.showPage(fTypeMethodsSplitter); } } private void processOutstandingEvents() { Display display= getDisplay(); if (display != null && !display.isDisposed()) display.update(); } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(false); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); fMethodsViewer.dispose(); if (fPropertyChangeListener != null) { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } getSite().getPage().removePartListener(fPartListener); if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } /** * Answer the property defined by key. */ public Object getAdapter(Class key) { if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(key); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); KeyListener keyListener= createKeyListener(); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW); fAllViewers= new TypeHierarchyViewer[3]; fAllViewers[VIEW_ID_SUPER]= superTypesViewer; fAllViewers[VIEW_ID_SUB]= subTypesViewer; fAllViewers[VIEW_ID_TYPE]= vajViewer; int currViewerIndex; try { currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW); if (currViewerIndex < 0 || currViewerIndex > 2) { currViewerIndex= VIEW_ID_TYPE; } } catch (NumberFormatException e) { currViewerIndex= VIEW_ID_TYPE; } fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setInput(fAllViewers[i]); } // force the update fCurrentViewerIndex= -1; setView(currViewerIndex); return fViewerbook; } private KeyListener createKeyListener() { return new KeyAdapter() { public void keyReleased(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F5) { updateHierarchyViewer(false); return; } else if (event.character == SWT.DEL){ if (fCCPActionGroup.getDeleteAction().isEnabled()) fCCPActionGroup.getDeleteAction().run(); return; } } viewPartKeyShortcuts(event); } }; } private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) { typesViewer.getControl().setVisible(false); typesViewer.getControl().addKeyListener(keyListener); typesViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillTypesViewerContextMenu(typesViewer, menu); } }, cotextHelpId, getSite()); typesViewer.addSelectionChangedListener(fSelectionChangedListener); typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames()); } private Control createMethodViewerControl(Composite parent) { fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this); fMethodsViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillMethodsViewerContextMenu(menu); } }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite()); fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener); Control control= fMethodsViewer.getTable(); control.addKeyListener(createKeyListener()); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK; for (int i= 0; i < fAllViewers.length; i++) { addDragAdapters(fAllViewers[i], ops, transfers); addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers); } addDragAdapters(fMethodsViewer, ops, transfers); //dnd on empty hierarchy DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT); dropTarget.setTransfer(transfers); dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0])); } private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){ TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new TypeHierarchyTransferDropAdapter(this, viewer) }; viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners)); } private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){ Control control= viewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(viewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners)); } private void viewPartKeyShortcuts(KeyEvent event) { if (event.stateMask == SWT.CTRL) { if (event.character == '1') { setView(VIEW_ID_TYPE); } else if (event.character == '2') { setView(VIEW_ID_SUPER); } else if (event.character == '3') { setView(VIEW_ID_SUB); } } } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ MenuManager menu= new MenuManager(); menu.add(fFocusOnTypeAction); fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel)); fPagebook.showPage(fNoHierarchyShownLabel); int orientation; try { orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION); if (orientation < 0 || orientation > 2) { orientation= VIEW_ORIENTATION_VERTICAL; } } catch (NumberFormatException e) { orientation= VIEW_ORIENTATION_VERTICAL; } // force the update fCurrentOrientation= -1; // will fill the main tool bar setOrientation(orientation); if (fMemento != null) { // restore state before creating action restoreLinkingEnabled(fMemento); } fToggleLinkingAction= new ToggleLinkingAction(this); // set the filter menu items IActionBars actionBars= getViewSite().getActionBars(); IMenuManager viewMenu= actionBars.getMenuManager(); for (int i= 0; i < fToggleOrientationActions.length; i++) { viewMenu.add(fToggleOrientationActions[i]); } viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); viewMenu.add(fShowQualifiedTypeNamesAction); viewMenu.add(fToggleLinkingAction); // fill the method viewer toolbar ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar); lowertbmanager.add(fEnableMemberFilterAction); lowertbmanager.add(new Separator()); fMethodsViewer.contributeToToolBar(lowertbmanager); lowertbmanager.update(true); // selection provider int nHierarchyViewers= fAllViewers.length; Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1]; for (int i= 0; i < nHierarchyViewers; i++) { trackedViewers[i]= fAllViewers[i]; } trackedViewers[nHierarchyViewers]= fMethodsViewer; fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager)); getSite().setSelectionProvider(fSelectionProviderMediator); getSite().getPage().addPartListener(fPartListener); IJavaElement input= determineInputElement(); if (fMemento != null) { restoreState(fMemento, input); } else if (input != null) { setInputElement(input); } else { setViewerVisibility(false); } WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); fActionGroups= new CompositeActionGroup(new ActionGroup[] { new NewWizardsActionGroup(this.getSite()), new OpenEditorActionGroup(this), new OpenViewActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new GenerateActionGroup(this), new JavaSearchActionGroup(this)}); fActionGroups.fillActionBars(actionBars); fSelectAllAction= new SelectAllAction(fMethodsViewer); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction); initDragAndDrop(); } /** * called from ToggleOrientationAction. * @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL */ public void setOrientation(int orientation) { if (fCurrentOrientation != orientation) { boolean methodViewerNeedsUpdate= false; if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed() && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) { if (orientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(false); enableMemberFilter(false); updateMethodViewer(null); } else { if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(true); methodViewerNeedsUpdate= true; } boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL; fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL); } updateMainToolbar(orientation); fTypeMethodsSplitter.layout(); } for (int i= 0; i < fToggleOrientationActions.length; i++) { fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation()); } fCurrentOrientation= orientation; if (methodViewerNeedsUpdate) { updateMethodViewer(fSelectedType); } fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation); } } private void updateMainToolbar(int orientation) { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager tbmanager= actionBars.getToolBarManager(); if (orientation == VIEW_ORIENTATION_HORIZONTAL) { clearMainToolBar(tbmanager); ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP); fillMainToolBar(new ToolBarManager(typeViewerToolBar)); fTypeViewerViewForm.setTopLeft(typeViewerToolBar); } else { fTypeViewerViewForm.setTopLeft(null); fillMainToolBar(tbmanager); } } private void fillMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.add(fHistoryDropDownAction); for (int i= 0; i < fViewActions.length; i++) { tbmanager.add(fViewActions[i]); } tbmanager.update(false); } private void clearMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.update(false); } /** * Creates the context menu for the hierarchy viewers */ private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) { JavaPlugin.createStandardGroups(menu); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS)); // viewer entries viewer.contributeToContextMenu(menu); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction); menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction); fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } /** * Creates the context menu for the method viewer */ private void fillMethodsViewerContextMenu(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries fMethodsViewer.contributeToContextMenu(menu); if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) { menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction); } fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } /** * Toggles between the empty viewer page and the hierarchy */ private void setViewerVisibility(boolean showHierarchy) { if (showHierarchy) { fViewerbook.showPage(getCurrentViewer().getControl()); } else { fViewerbook.showPage(fEmptyTypesViewer); } } /** * Sets the member filter. <code>null</code> disables member filtering. */ private void setMemberFilter(IMember[] memberFilter) { Assert.isNotNull(fAllViewers); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setMemberFilter(memberFilter); } } private IType getSelectableType(IJavaElement elem) { if (elem.getElementType() != IJavaElement.TYPE) { return null; //(IType) getCurrentViewer().getTreeRootType(); } else { return (IType) elem; } } private void internalSelectType(IMember elem, boolean reveal) { TypeHierarchyViewer viewer= getCurrentViewer(); viewer.removeSelectionChangedListener(fSelectionChangedListener); viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal); viewer.addSelectionChangedListener(fSelectionChangedListener); } /** * When the input changed or the hierarchy pane becomes visible, * <code>updateHierarchyViewer<code> brings up the correct view and refreshes * the current tree */ private void updateHierarchyViewer(final boolean doExpand) { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(doExpand); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) { setViewerVisibility(true); } } else { fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$ setViewerVisibility(false); } } } private void updateMethodViewer(final IType input) { if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input == fMethodsViewer.getInput()) { if (input != null) { Runnable runnable= new Runnable() { public void run() { fMethodsViewer.refresh(); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); } } else { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } Runnable runnable= new Runnable() { public void run() { fMethodsViewer.setInput(input); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); } } } protected void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); fSelectAllAction.setEnabled(true); } else { typeSelectionChanged(e.getSelection()); fSelectAllAction.setEnabled(false); } } private void methodSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (fIsEnableMemberFilter) { IMember[] memberFilter= null; if (nSelected > 0) { memberFilter= new IMember[nSelected]; selected.toArray(memberFilter); } setMemberFilter(memberFilter); updateHierarchyViewer(true); updateTitle(); internalSelectType(fSelectedType, true); } if (nSelected == 1) { revealElementInEditor(selected.get(0), fMethodsViewer); } } } private void typeSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (nSelected != 0) { List types= new ArrayList(nSelected); for (int i= nSelected-1; i >= 0; i--) { Object elem= selected.get(i); if (elem instanceof IType && !types.contains(elem)) { types.add(elem); } } if (types.size() == 1) { fSelectedType= (IType) types.get(0); updateMethodViewer(fSelectedType); } else if (types.size() == 0) { // method selected, no change } if (nSelected == 1) { revealElementInEditor(selected.get(0), getCurrentViewer()); } } else { fSelectedType= null; updateMethodViewer(null); } } } private void revealElementInEditor(Object elem, Viewer originViewer) { // only allow revealing when the type hierarchy is the active pagae // no revealing after selection events due to model changes if (getSite().getPage().getActivePart() != this) { return; } if (fSelectionProviderMediator.getViewerInFocus() != originViewer) { return; } IEditorPart editorPart= EditorUtility.isOpenInEditor(elem); if (editorPart != null && (elem instanceof IJavaElement)) { getSite().getPage().removePartListener(fPartListener); getSite().getPage().bringToTop(editorPart); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } } private Display getDisplay() { if (fPagebook != null && !fPagebook.isDisposed()) { return fPagebook.getDisplay(); } return null; } private boolean isChildVisible(Composite pb, Control child) { Control[] children= pb.getChildren(); for (int i= 0; i < children.length; i++) { if (children[i] == child && children[i].isVisible()) return true; } return false; } private void updateTitle() { String viewerTitle= getCurrentViewer().getTitle(); String tooltip; String title; if (fInputElement != null) { String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) }; title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$ tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$ } else { title= viewerTitle; tooltip= viewerTitle; } setTitle(title); setTitleToolTip(tooltip); } private void updateToolbarButtons() { boolean isType= fInputElement instanceof IType; for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; if (action.getViewerIndex() == VIEW_ID_TYPE) { action.setEnabled(fInputElement != null); } else { action.setEnabled(isType); } } } /** * Sets the current view (see view id) * called from ToggleViewAction. Must be called after creation of the viewpart. */ public void setView(int viewerIndex) { Assert.isNotNull(fAllViewers); if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) { fCurrentViewerIndex= viewerIndex; updateHierarchyViewer(false); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { internalSelectType(getSelectableType(fInputElement), false); currSelection= getCurrentViewer().getSelection(); } if (!fIsEnableMemberFilter) { typeSelectionChanged(currSelection); } } updateTitle(); fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex); getCurrentViewer().getTree().setFocus(); } for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; action.setChecked(fCurrentViewerIndex == action.getViewerIndex()); } } /** * Gets the curret active view index. */ public int getViewIndex() { return fCurrentViewerIndex; } private TypeHierarchyViewer getCurrentViewer() { return fAllViewers[fCurrentViewerIndex]; } /** * called from EnableMemberFilterAction. * Must be called after creation of the viewpart. */ public void enableMemberFilter(boolean on) { if (on != fIsEnableMemberFilter) { fIsEnableMemberFilter= on; if (!on) { IType methodViewerInput= (IType) fMethodsViewer.getInput(); setMemberFilter(null); updateHierarchyViewer(true); updateTitle(); if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) { // avoid that the method view changes content by selecting the previous input internalSelectType(methodViewerInput, true); } else if (fSelectedType != null) { // choose a input that exists internalSelectType(fSelectedType, true); updateMethodViewer(fSelectedType); } } else { methodSelectionChanged(fMethodsViewer.getSelection()); } } fEnableMemberFilterAction.setChecked(on); } /** * called from ShowQualifiedTypeNamesAction. Must be called after creation * of the viewpart. */ public void showQualifiedTypeNames(boolean on) { if (fAllViewers == null) { return; } for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setQualifiedTypeName(on); } } private boolean isShowQualifiedTypeNames() { return fShowQualifiedTypeNamesAction.isChecked(); } /** * Called from ITypeHierarchyLifeCycleListener. * Can be called from any thread */ protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { if (!fIsVisible) { fNeedRefresh= true; } Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { if (fPagebook != null && !fPagebook.isDisposed()) { doTypeHierarchyChangedOnViewers(changedTypes); } } }); } } protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } fMethodsViewer.refresh(); updateHierarchyViewer(false); } else { // elements in hierarchy modified fMethodsViewer.refresh(); if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(false); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { IJavaElement elem= (IJavaElement) input; if (elem instanceof IMember) { return elem; } else { int kind= elem.getElementType(); if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) { return elem; } } } return null; } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { String handleIndentifier= fInputElement.getHandleIdentifier(); if (fInputElement instanceof IType) { ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) { // for startup performance reasons do not try to recover huge hierarchies handleIndentifier= null; } } memento.putString(TAG_INPUT, handleIndentifier); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fMethodsViewer.saveState(memento); saveLinkingEnabled(memento); } private void saveLinkingEnabled(IMemento memento) { memento.putInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, fLinkingEnabled ? 1 : 0); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (input != null && !input.exists()) { input= null; } } setInputElement(input); Integer viewerIndex= memento.getInteger(TAG_VIEW); if (viewerIndex != null) { setView(viewerIndex.intValue()); } Integer orientation= memento.getInteger(TAG_ORIENTATION); if (orientation != null) { setOrientation(orientation.intValue()); } Integer ratio= memento.getInteger(TAG_RATIO); if (ratio != null) { fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() }); } ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } //String selectionId= memento.getString(TAG_SELECTION); // do not restore type hierarchy contents // if (selectionId != null) { // IJavaElement elem= JavaCore.create(selectionId); // if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) { // internalSelectType((IMember)elem, false); // } // } fMethodsViewer.restoreState(memento); } private void restoreLinkingEnabled(IMemento memento) { Integer val= memento.getInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR); if (val != null) { fLinkingEnabled= val.intValue() != 0; } } /** * view part becomes visible */ protected void visibilityChanged(boolean isVisible) { fIsVisible= isVisible; if (isVisible && fNeedRefresh) { doTypeHierarchyChanged(fHierarchyLifeCycle, null); } fNeedRefresh= false; } /** * Link selection to active editor. */ protected void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) { return; } if (fInputElement == null) { // no type hierarchy shown return; } IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class); try { TypeHierarchyViewer currentViewer= getCurrentViewer(); if (elem instanceof IClassFile) { IType type= ((IClassFile)elem).getType(); if (currentViewer.isElementShown(type)) { internalSelectType(type, true); updateMethodViewer(type); } } else if (elem instanceof ICompilationUnit) { IType[] allTypes= ((ICompilationUnit)elem).getAllTypes(); for (int i= 0; i < allTypes.length; i++) { if (currentViewer.isElementShown(allTypes[i])) { internalSelectType(allTypes[i], true); updateMethodViewer(allTypes[i]); return; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return fInputElement; } /** * Returns the <code>IShowInSource</code> for this view. */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( null, getSite().getSelectionProvider().getSelection()); } }; } boolean isLinkingEnabled() { return fLinkingEnabled; } public void setLinkingEnabled(boolean enabled) { fLinkingEnabled= enabled; if (enabled) { IEditorPart editor = getSite().getPage().getActiveEditor(); if (editor != null) { editorActivated(editor); } } } }
18,588
Bug 18588 [Workbench] Hierarchy - no progress monitor ?
Build 20020601 Open type java.lang.Object, select Object type name in editor, and hit F4. No progress is shown during hierarchy opening.
resolved wontfix
3937701
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T18:40:40Z
2002-06-01T14:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/OpenTypeHierarchyUtil.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.util; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.util.Assert; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.WorkbenchException; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.actions.OpenActionUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart; public class OpenTypeHierarchyUtil { private OpenTypeHierarchyUtil() { } public static TypeHierarchyViewPart open(IJavaElement element, IWorkbenchWindow window) { IJavaElement[] candidates= getCandidates(element); if (candidates != null) { return open(candidates, window); } return null; } public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) { Assert.isTrue(candidates != null && candidates.length != 0); IJavaElement input= null; if (candidates.length > 1) { String title= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message"); //$NON-NLS-1$ input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message); } else { input= candidates[0]; } if (input == null) return null; try { if (PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.OPEN_TYPE_HIERARCHY))) { return openInPerspective(window, input); } else { return openInViewPart(window, input); } } catch (WorkbenchException e) { ExceptionHandler.handle(e, window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$ e.getMessage()); } catch (JavaModelException e) { ExceptionHandler.handle(e, window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$ e.getMessage()); } return null; } private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) { IWorkbenchPage page= window.getActivePage(); try { // 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) { ExceptionHandler.handle(e, window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$ } return null; } private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement input) throws WorkbenchException, JavaModelException { IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); // The problem is that the input element can be a working copy. So we first convert it to the original element if // it exists. IJavaElement perspectiveInput= input; if (input instanceof IMember) { ICompilationUnit cu= ((IMember)input).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { IJavaElement je= cu.getOriginal(input); if (je != null) input= je; } perspectiveInput= input; if (input.getElementType() != IJavaElement.TYPE) { perspectiveInput= ((IMember)input).getDeclaringType(); } else { perspectiveInput= input; } } IWorkbenchPage page= workbench.showPerspective(JavaUI.ID_HIERARCHYPERSPECTIVE, window, perspectiveInput); 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); } /** * Converts the input to a possible input candidates */ public static IJavaElement[] getCandidates(Object input) { if (!(input instanceof IJavaElement)) { return null; } try { IJavaElement elem= (IJavaElement) input; switch (elem.getElementType()) { case IJavaElement.INITIALIZER: case IJavaElement.METHOD: case IJavaElement.FIELD: case IJavaElement.TYPE: case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.JAVA_PROJECT: return new IJavaElement[] { elem }; case IJavaElement.PACKAGE_FRAGMENT: if (((IPackageFragment)elem).containsJavaResources()) return new IJavaElement[] {elem}; break; case IJavaElement.PACKAGE_DECLARATION: return new IJavaElement[] { elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT) }; case IJavaElement.IMPORT_DECLARATION: IImportDeclaration decl= (IImportDeclaration) elem; if (decl.isOnDemand()) { elem= JavaModelUtil.findTypeContainer(elem.getJavaProject(), Signature.getQualifier(elem.getElementName())); } else { elem= elem.getJavaProject().findType(elem.getElementName()); } if (elem == null) return null; return new IJavaElement[] {elem}; case IJavaElement.CLASS_FILE: return new IJavaElement[] { ((IClassFile)input).getType() }; case IJavaElement.COMPILATION_UNIT: { ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { IType[] types= cu.getTypes(); if (types.length > 0) { return types; } } break; } default: } } catch (JavaModelException e) { JavaPlugin.log(e); } return null; } }
32,268
Bug 32268 Filtering by closed projects removes files from Packages Explorer
build i2003-02-18 (1130), win2k, j9sc20030214 I have filters turned on so I don't see Closed projects. No files in the root of my project show up in the Packages Explorer. (plugin.xml, build.properties, etc etc)
resolved fixed
646b945
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T20:31:31Z
2003-02-19T18:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/ClosedProjectFilter.java
32,273
Bug 32273 StringIndexOutOfBoundsException in JUnit plugin [JUnit]
Using 0218 and Pde/Junit1.2.4, I got the following exception. java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1480) at org.eclipse.jdt.internal.junit.ui.FailureRunView.getClassName(FailureRunView.java:105) at org.eclipse.jdt.internal.junit.ui.FailureRunView.handleDoubleClick(FailureRunView.java:243) at org.eclipse.jdt.internal.junit.ui.FailureRunView$3.mouseDoubleClick(FailureRunView.java:205) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:134) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1288) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1271) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) I have no steps to reproduce so far, but I think it's worth logging a PR.
resolved fixed
6d0f0c9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-19T22:32:03Z
2003-02-19T18:40:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureRunView.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jdt.junit.ITestRunListener; /** * A view presenting the failed tests in a table. */ class FailureRunView implements ITestRunView, IMenuListener { private Table fTable; private TestRunnerViewPart fRunnerViewPart; private boolean fPressed= false; private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$ private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$ private final Image fFailureTabIcon= TestRunnerViewPart.createImage("obj16/failures.gif"); //$NON-NLS-1$ public FailureRunView(CTabFolder tabFolder, TestRunnerViewPart runner) { fRunnerViewPart= runner; CTabItem failureTab= new CTabItem(tabFolder, SWT.NONE); failureTab.setText(getName()); failureTab.setImage(fFailureTabIcon); Composite composite= new Composite(tabFolder, SWT.NONE); GridLayout gridLayout= new GridLayout(); gridLayout.marginHeight= 0; gridLayout.marginWidth= 0; composite.setLayout(gridLayout); GridData gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL); composite.setLayoutData(gridData); fTable= new Table(composite, SWT.NONE); gridLayout= new GridLayout(); gridLayout.marginHeight= 0; gridLayout.marginWidth= 0; fTable.setLayout(gridLayout); gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL); fTable.setLayoutData(gridData); failureTab.setControl(composite); failureTab.setToolTipText(JUnitMessages.getString("FailureRunView.tab.tooltip")); //$NON-NLS-1$ initMenu(); addListeners(); } void disposeIcons() { fErrorIcon.dispose(); fFailureIcon.dispose(); fFailureTabIcon.dispose(); } private void initMenu() { MenuManager menuMgr= new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); Menu menu= menuMgr.createContextMenu(fTable); fTable.setMenu(menu); } public String getName() { return JUnitMessages.getString("FailureRunView.tab.title"); //$NON-NLS-1$ } public String getTestName() { int index= fTable.getSelectionIndex(); if (index == -1) return null; return fTable.getItem(index).getText(); } private String getClassName() { String className= getSelectedText(); className= className.substring(className.indexOf('(') + 1); return className.substring(0, className.indexOf(')')); } private String getMethodName() { String methodName= getSelectedText(); return methodName.substring(0, methodName.indexOf('(')); } public void menuAboutToShow(IMenuManager manager){ if (fTable.getSelectionCount() > 0) { String className= getClassName(); String methodName= getMethodName(); if (className != null) { manager.add(new OpenTestAction(fRunnerViewPart, className, methodName)); manager.add(new RerunAction(fRunnerViewPart, className, methodName)); } } } private String getSelectedText() { int index= fTable.getSelectionIndex(); if (index == -1) return null; return fTable.getItem(index).getText(); } public void setSelectedTest(String testName){ TableItem[] items= fTable.getItems(); for (int i= 0; i < items.length; i++) { TableItem tableItem= items[i]; if (tableItem.getText().equals(testName)){ fTable.setSelection(new TableItem[] { tableItem }); fTable.showItem(tableItem); return; } } } public void setFocus() { fTable.setFocus(); } public void endTest(String testName){ TestRunInfo testInfo= fRunnerViewPart.getTestInfo(testName); if(testInfo == null || testInfo.fStatus == ITestRunListener.STATUS_OK) return; TableItem tableItem= new TableItem(fTable, SWT.NONE); updateTableItem(testInfo, tableItem); fTable.showItem(tableItem); } private void updateTableItem(TestRunInfo testInfo, TableItem tableItem) { tableItem.setText(testInfo.fTestName); if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE) tableItem.setImage(fFailureIcon); else tableItem.setImage(fErrorIcon); tableItem.setData(testInfo); } private TableItem findItemByTest(String testName) { TableItem[] items= fTable.getItems(); for (int i= 0; i < items.length; i++) { if (items[i].getText().equals(testName)) return items[i]; } return null; } public void activate() { testSelected(); } public void aboutToStart() { fTable.removeAll(); } protected void testSelected() { fRunnerViewPart.handleTestSelected(getTestName()); } protected void addListeners() { fTable.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { activate(); } public void widgetDefaultSelected(SelectionEvent e) { activate(); } }); fTable.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { disposeIcons(); } }); fTable.addMouseListener(new MouseListener() { public void mouseDoubleClick(MouseEvent e){ handleDoubleClick(e); } public void mouseDown(MouseEvent e) { fPressed= true; activate(); } public void mouseUp(MouseEvent e) { fPressed= false; activate(); } }); fTable.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { TableItem tableItem= ((Table) e.getSource()).getItem(new Point(e.x, e.y)); if (fPressed & (null != tableItem)) { fTable.setSelection(new TableItem[] { tableItem }); activate(); } // scrolling up and down if ((e.y + 1 > fTable.getBounds().height) & fPressed & (fTable.getSelectionIndex() != fTable.getItemCount() - 1)) { fTable.setTopIndex(fTable.getTopIndex() + 1); fTable.setSelection(fTable.getSelectionIndex() + 1); activate(); } if ((e.y - 1 < 0) & fPressed & (fTable.getTopIndex() != 0)) { fTable.setTopIndex(fTable.getTopIndex() - 1); fTable.setSelection(fTable.getSelectionIndex() - 1); activate(); } } }); } public void handleDoubleClick(MouseEvent e) { if (fTable.getSelectionCount() > 0) new OpenTestAction(fRunnerViewPart, getClassName(), getMethodName()).run(); } public void newTreeEntry(String treeEntry) { } /* * @see ITestRunView#testStatusChanged(TestRunInfo) */ public void testStatusChanged(TestRunInfo info) { TableItem item= findItemByTest(info.fTestName); if (item != null) { if (info.fStatus == ITestRunListener.STATUS_OK) { item.dispose(); return; } updateTableItem(info, item); } if (item == null && info.fStatus != ITestRunListener.STATUS_OK) { item= new TableItem(fTable, SWT.NONE); updateTableItem(info, item); } if (item != null) fTable.showItem(item); } }
32,224
Bug 32224 [Show In]Back-linking doesn't work for .class files in jars
Build 20030218 1. Enable back-linking in Package Explorer 2. Open Object (in rt.jar) Observe: An editor on Object.class opens (it shows the attached source). However Object.class is not shown in Package Explorer Note that Alt-Shift-s->Package Explorer doesn't work either.
resolved fixed
4826918
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T08:22:34Z
2003-02-19T13:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ITreeViewerListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeExpansionEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.core.runtime.IPath; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTarget; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ISetSelectionTarget; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.ui.IPackagesViewPart; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; /** * The ViewPart for the ProjectExplorer. It listens to part activation events. * When selection linking with the editor is enabled the view selection tracks * the active editor page. Similarly when a resource is selected in the packages * view the corresponding editor is activated. */ public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IShowInTarget, IPackagesViewPart, IPropertyChangeListener, IViewPartInputProvider { private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical private static final int HIERARCHICAL_LAYOUT= 0x1; private static final int FLAT_LAYOUT= 0x2; public final static String VIEW_ID= JavaUI.ID_PACKAGES; // Persistance tags. static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$ static final String TAG_ELEMENT= "element"; //$NON-NLS-1$ static final String TAG_PATH= "path"; //$NON-NLS-1$ static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$ static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$ static final String TAG_FILTERS = "filters"; //$NON-NLS-1$ static final String TAG_FILTER = "filter"; //$NON-NLS-1$ static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$ private PackageExplorerContentProvider fContentProvider; private PackageExplorerActionGroup fActionSet; private ProblemTreeViewer fViewer; private Menu fContextMenu; private IMemento fMemento; private ISelectionChangedListener fSelectionListener; private String fWorkingSetName; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; private ITreeViewerListener fExpansionListener= new ITreeViewerListener() { public void treeCollapsed(TreeExpansionEvent event) { } public void treeExpanded(TreeExpansionEvent event) { Object element= event.getElement(); if (element instanceof ICompilationUnit || element instanceof IClassFile) expandMainType(element); } }; private PackageExplorerLabelProvider fLabelProvider; /* (non-Javadoc) * Method declared on IViewPart. */ private boolean fLinkingEnabled; public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; restoreLayoutState(memento); } private void restoreLayoutState(IMemento memento) { Integer state= null; if (memento != null) state= memento.getInteger(TAG_LAYOUT); // If no memento try an restore from preference store if(state == null) { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); state= new Integer(store.getInt(TAG_LAYOUT)); } if (state.intValue() == FLAT_LAYOUT) fIsCurrentLayoutFlat= true; else if (state.intValue() == HIERARCHICAL_LAYOUT) fIsCurrentLayoutFlat= false; else fIsCurrentLayoutFlat= true; } /** * Returns the package explorer part of the active perspective. If * there isn't any package explorer part <code>null</code> is returned. */ public static PackageExplorerPart getFromActivePerspective() { IWorkbenchPage activePage= JavaPlugin.getActivePage(); if (activePage == null) return null; IViewPart view= activePage.findView(VIEW_ID); if (view instanceof PackageExplorerPart) return (PackageExplorerPart)view; return null; } /** * Makes the package explorer part visible in the active perspective. If there * isn't a package explorer part registered <code>null</code> is returned. * Otherwise the opened view part is returned. */ public static PackageExplorerPart openInActivePerspective() { try { return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID); } catch(PartInitException pe) { return null; } } public void dispose() { if (fContextMenu != null && !fContextMenu.isDisposed()) fContextMenu.dispose(); getSite().getPage().removePartListener(fPartListener); JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); if (fViewer != null) fViewer.removeTreeListener(fExpansionListener); if (fActionSet != null) fActionSet.dispose(); super.dispose(); } /** * Implementation of IWorkbenchPart.createPartControl(Composite) */ public void createPartControl(Composite parent) { fViewer= createViewer(parent); fViewer.setUseHashlookup(true); fViewer.setComparer(new PackageExplorerElementComparer()); setProviders(); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getTree()); fViewer.getTree().setMenu(fContextMenu); // Register viewer with site. This must be done before making the actions. IWorkbenchPartSite site= getSite(); site.registerContextMenu(menuMgr, fViewer); site.setSelectionProvider(fViewer); site.getPage().addPartListener(fPartListener); if (fMemento != null) { restoreLinkingEnabled(fMemento); } makeActions(); // call before registering for selection changes // Set input after filter and sorter has been set. This avoids resorting and refiltering. restoreFilterAndSorter(); fViewer.setInput(findInputElement()); initDragAndDrop(); initKeyListener(); fSelectionListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { handleSelectionChanged(event); } }; fViewer.addSelectionChangedListener(fSelectionListener); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { fActionSet.handleDoubleClick(event); } }); fViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { fActionSet.handleOpen(event); } }); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); fViewer.addTreeListener(fExpansionListener); if (fMemento != null) restoreUIState(fMemento); fMemento= null; // Set help for the view JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW); fillActionBars(); updateTitle(); } /** * This viewer ensures that non-leaves in the hierarchical * layout are not removed by any filters. * * @since 2.1 */ private ProblemTreeViewer createViewer(Composite parent) { return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) { /* * @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object) */ protected Object[] getFilteredChildren(Object parent) { List list = new ArrayList(); ViewerFilter[] filters = fViewer.getFilters(); Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent); for (int i = 0; i < children.length; i++) { Object object = children[i]; if (!isEssential(object)) { object = filter(object, parent, filters); if (object != null) { list.add(object); } } else list.add(object); } return list.toArray(); } // Sends the object through the given filters private Object filter(Object object, Object parent, ViewerFilter[] filters) { for (int i = 0; i < filters.length; i++) { ViewerFilter filter = filters[i]; if (!filter.select(fViewer, parent, object)) return null; } return object; } /* Checks if a filtered object in essential (ie. is a parent that * should not be removed). */ private boolean isEssential(Object object) { try { if (!isFlatLayout() && object instanceof IPackageFragment) { IPackageFragment fragment = (IPackageFragment) object; return !fragment.isDefaultPackage() && fragment.hasSubpackages(); } } catch (JavaModelException e) { JavaPlugin.log(e); } return false; } }; } /** * Answers whether this part shows the packages flat or hierarchical. * * @since 2.1 */ boolean isFlatLayout() { return fIsCurrentLayoutFlat; } private void setProviders() { //content provider must be set before the label provider fContentProvider= createContentProvider(); fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setContentProvider(fContentProvider); fLabelProvider= createLabelProvider(); fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false)); // problem decoration provided by PackageLabelProvider } void toggleLayout() { // Update current state and inform content and label providers fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat; saveLayoutState(null); fContentProvider.setIsFlatLayout(isFlatLayout()); fLabelProvider.setIsFlatLayout(isFlatLayout()); fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } /** * This method should only be called inside this class * and from test cases. */ public PackageExplorerContentProvider createContentProvider() { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS)); return new PackageExplorerContentProvider(showCUChildren, reconcile); } private PackageExplorerLabelProvider createLabelProvider() { return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, fContentProvider); } private void fillActionBars() { IActionBars actionBars= getViewSite().getActionBars(); fActionSet.fillActionBars(actionBars); } private Object findInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IWorkspace) { return JavaCore.create(((IWorkspace)input).getRoot()); } else if (input instanceof IContainer) { IJavaElement element= JavaCore.create((IContainer)input); if (element != null && element.exists()) return element; return input; } //1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective // we can't handle the input // fall back to show the workspace return JavaCore.create(JavaPlugin.getWorkspace().getRoot()); } /** * Answer the property defined by key. */ public Object getAdapter(Class key) { if (key.equals(ISelectionProvider.class)) return fViewer; if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(key); } /** * Returns the tool tip text for the given element. */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$ } else { result= path.makeRelative().toString(); } } if (fWorkingSetName == null) return result; String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$ if (result.length() == 0) return wsstr; return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$ } public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } /** * @see IWorkbenchPart#setFocus() */ public void setFocus() { fViewer.getTree().setFocus(); } /** * Returns the current selection. */ private ISelection getSelection() { return fViewer.getSelection(); } //---- Action handling ---------------------------------------------------------- /** * Called when the context menu is about to open. Override * to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); fActionSet.setContext(new ActionContext(getSelection())); fActionSet.fillContextMenu(menu); fActionSet.setContext(null); } private void makeActions() { fActionSet= new PackageExplorerActionGroup(this); } //---- Event handling ---------------------------------------------------------- private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance(), FileTransfer.getInstance()}; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fViewer), new FileTransferDropAdapter(fViewer) }; fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); // Drag Adapter Control control= fViewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fViewer), new ResourceTransferDragAdapter(fViewer), new FileTransferDragAdapter(fViewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners) { public void dragStart(DragSourceEvent event) { IStructuredSelection selection= (IStructuredSelection)getSelection(); if (selection.isEmpty()) { event.doit= false; return; } for (Iterator iter= selection.iterator(); iter.hasNext(); ) { if (iter.next() instanceof IMember) { setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)}); break; } } super.dragStart(event); } }); } /** * Handles selection changed in viewer. * Updates global actions. * Links to editor (if option enabled) */ private void handleSelectionChanged(SelectionChangedEvent event) { IStructuredSelection selection= (IStructuredSelection) event.getSelection(); fActionSet.handleSelectionChanged(event); // if (OpenStrategy.getOpenMethod() != OpenStrategy.SINGLE_CLICK) linkToEditor(selection); } public void selectReveal(ISelection selection) { selectReveal(selection, 0); } private void selectReveal(final ISelection selection, final int count) { Control ctrl= getViewer().getControl(); if (ctrl == null || ctrl.isDisposed()) return; ISelection javaSelection= convertSelection(selection); fViewer.setSelection(javaSelection, true); PackageExplorerContentProvider provider= (PackageExplorerContentProvider)getViewer().getContentProvider(); ISelection cs= fViewer.getSelection(); // If we have Pending changes and the element could not be selected then // we try it again on more time by posting the select and reveal asynchronuoulsy // to the event queue. See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=30700 // for a discussion of the underlying problem. if (count == 0 && provider.hasPendingChanges() && !javaSelection.equals(cs)) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { selectReveal(selection, count + 1); } }); } } private ISelection convertSelection(ISelection s) { if (!(s instanceof IStructuredSelection)) return s; Object[] elements= ((StructuredSelection)s).toArray(); if (!containsResources(elements)) return s; for (int i= 0; i < elements.length; i++) { Object o= elements[i]; if (o instanceof IResource) { IJavaElement jElement= JavaCore.create((IResource)o); if (jElement != null && jElement.exists()) elements[i]= jElement; } } return new StructuredSelection(elements); } private boolean containsResources(Object[] elements) { for (int i = 0; i < elements.length; i++) { if (elements[i] instanceof IResource) return true; } return false; } public void selectAndReveal(Object element) { selectReveal(new StructuredSelection(element)); } boolean isLinkingEnabled() { return fLinkingEnabled; } /** * Initializes the linking enabled setting from the preference store. */ private void initLinkingEnabled() { fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { // ignore selection changes if the package explorer is not the active part. // In this case the selection change isn't triggered by a user. if (!isActivePart()) return; Object obj= selection.getFirstElement(); if (selection.size() == 1) { IEditorPart part= EditorUtility.isOpenInEditor(obj); if (part != null) { IWorkbenchPage page= getSite().getPage(); page.bringToTop(part); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) obj); } } } private boolean isActivePart() { return this == getSite().getPage().getActivePart(); } public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } saveExpansionState(memento); saveSelectionState(memento); saveLayoutState(memento); saveLinkingEnabled(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //saveScrollState(memento, fViewer.getTree()); fActionSet.saveFilterAndSorterState(memento); } private void saveLinkingEnabled(IMemento memento) { memento.putInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, fLinkingEnabled ? 1 : 0); } /** * Saves the current layout state. * * @param memento the memento to save the state into or * <code>null</code> to store the state in the preferences * @since 2.1 */ private void saveLayoutState(IMemento memento) { if (memento != null) { memento.putInteger(TAG_LAYOUT, getLayoutAsInt()); } else { //if memento is null save in preference store IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(TAG_LAYOUT, getLayoutAsInt()); } } private int getLayoutAsInt() { if (fIsCurrentLayoutFlat) return FLAT_LAYOUT; else return HIERARCHICAL_LAYOUT; } protected void saveScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position)); //save horizontal position bar= tree.getHorizontalBar(); position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position)); } protected void saveSelectionState(IMemento memento) { Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray(); if (elements.length > 0) { IMemento selectionMem= memento.createChild(TAG_SELECTION); for (int i= 0; i < elements.length; i++) { IMemento elementMem= selectionMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= elements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier()); } } } protected void saveExpansionState(IMemento memento) { Object expandedElements[]= fViewer.getVisibleExpandedElements(); if (expandedElements.length > 0) { IMemento expandedMem= memento.createChild(TAG_EXPANDED); for (int i= 0; i < expandedElements.length; i++) { IMemento elementMem= expandedMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= expandedElements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier()); } } } private void restoreFilterAndSorter() { fViewer.setSorter(new JavaElementSorter()); if (fMemento != null) fActionSet.restoreFilterAndSorterState(fMemento); } private void restoreUIState(IMemento memento) { restoreExpansionState(memento); restoreSelectionState(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //restoreScrollState(memento, fViewer.getTree()); } private void restoreLinkingEnabled(IMemento memento) { Integer val= memento.getInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); if (val != null) { fLinkingEnabled= val.intValue() != 0; } } protected void restoreScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_VERTICAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore, don't set scrollposition } } bar= tree.getHorizontalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_HORIZONTAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore don't set scroll position } } } protected void restoreSelectionState(IMemento memento) { IMemento childMem; childMem= memento.getChild(TAG_SELECTION); if (childMem != null) { ArrayList list= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) list.add(element); } fViewer.setSelection(new StructuredSelection(list)); } } protected void restoreExpansionState(IMemento memento) { IMemento childMem= memento.getChild(TAG_EXPANDED); if (childMem != null) { ArrayList elements= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) elements.add(element); } fViewer.setExpandedElements(elements.toArray()); } } /** * Create the KeyListener for doing the refresh on the viewer. */ private void initKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { fActionSet.handleKeyEvent(event); } }); } /** * An editor has been activated. Set the selection in this Packages Viewer * to be the editor's input, if linking is enabled. */ void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) return; showInput(getElementOfInput(editor.getEditorInput())); } boolean showInput(Object input) { Object element= null; if (input instanceof IFile) 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 IJavaElement) { ICompilationUnit cu= (ICompilationUnit)((IJavaElement)o).getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { if (cu.isWorkingCopy()) cu= (ICompilationUnit)cu.getOriginalElement(); if ( element.equals(cu)) return false; } IClassFile cf= (IClassFile)((IJavaElement)o).getAncestor(IJavaElement.CLASS_FILE); if (cf != null && element.equals(cf)) return false; } } ISelection newSelection= new StructuredSelection(element); if (!fViewer.getSelection().equals(newSelection)) { try { fViewer.removeSelectionChangedListener(fSelectionListener); fViewer.setSelection(newSelection); while (element != null && fViewer.getSelection().isEmpty()) { // Try to select parent in case element is filtered element= getParent(element); if (element != null) { newSelection= new StructuredSelection(element); fViewer.setSelection(newSelection); } } } finally { fViewer.addSelectionChangedListener(fSelectionListener); } return true; } } return false; } /** * Returns the element's parent. * * @return the parent or <code>null</code> if there's no parent */ private Object getParent(Object element) { if (element instanceof IJavaElement) return ((IJavaElement)element).getParent(); else if (element instanceof IResource) return ((IResource)element).getParent(); // else if (element instanceof IStorage) { // can't get parent - see bug 22376 // } return null; } /** * A compilation unit or class was expanded, expand * the main type. */ void expandMainType(Object element) { try { IType type= null; if (element instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit)element; IType[] types= cu.getTypes(); if (types.length > 0) type= types[0]; } else if (element instanceof IClassFile) { IClassFile cf= (IClassFile)element; type= cf.getType(); } if (type != null) { final IType type2= type; Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) fViewer.expandToLevel(type2, 1); } }); } } } catch(JavaModelException e) { // no reveal } } /** * Returns the element contained in the EditorInput */ Object getElementOfInput(IEditorInput input) { if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); else if (input instanceof IFileEditorInput) return ((IFileEditorInput)input).getFile(); else if (input instanceof JarEntryEditorInput) return ((JarEntryEditorInput)input).getStorage(); return null; } /** * Returns the Viewer. */ TreeViewer getViewer() { return fViewer; } /** * Returns the TreeViewer. */ public TreeViewer getTreeViewer() { return fViewer; } boolean isExpandable(Object element) { if (fViewer == null) return false; return fViewer.isExpandable(element); } void setWorkingSetName(String workingSetName) { fWorkingSetName= workingSetName; } /** * Updates the title text and title tool tip. * Called whenever the input of the viewer changes. */ void updateTitle() { Object input= fViewer.getInput(); String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ if (input == null || (input instanceof IJavaModel)) { setTitle(viewName); setTitleToolTip(""); //$NON-NLS-1$ } else { String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$ setTitle(title); setTitleToolTip(getToolTipText(input)); } } /** * Sets the decorator for the package explorer. * * @param decorator a label decorator or <code>null</code> for no decorations. * @deprecated To be removed */ public void setLabelDecorator(ILabelDecorator decorator) { } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fViewer == null) return; boolean refreshViewer= false; if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) { fActionSet.updateActionBars(getViewSite().getActionBars()); boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); ((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren); refreshViewer= true; } else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { refreshViewer= true; } if (refreshViewer) fViewer.refresh(); } /* (non-Javadoc) * @see IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { if (fViewer != null) { return fViewer.getInput(); } return null; } public void collapseAll() { fViewer.getControl().setRedraw(false); fViewer.collapseToLevel(getViewPartInput(), TreeViewer.ALL_LEVELS); fViewer.getControl().setRedraw(true); } public PackageExplorerPart() { initLinkingEnabled(); } public boolean show(ShowInContext context) { Object input= context.getInput(); if (input instanceof IEditorInput) return showInput(getElementOfInput((IEditorInput)context.getInput())); ISelection selection= context.getSelection(); if (selection != null) { selectReveal(selection); return true; } return false; } /** * Returns the <code>IShowInSource</code> for this view. */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( getViewer().getInput(), getViewer().getSelection()); } }; } /** * @see IResourceNavigator#setLinkingEnabled(boolean) * @since 2.1 */ public void setLinkingEnabled(boolean enabled) { fLinkingEnabled= enabled; PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, enabled); if (enabled) { IEditorPart editor = getSite().getPage().getActiveEditor(); if (editor != null) { editorActivated(editor); } } } }
15,182
Bug 15182 junit: DND.ERROR_CANNOT_SET_CLIPBOARD must be handled
null
resolved fixed
89b1ecd
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T09:05:02Z
2002-05-03T12:46:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CopyTraceAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.ui; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jface.action.Action; /** * Copies a test failure stack trace to the clipboard. */ public class CopyTraceAction extends Action { private FailureTraceView fView; /** * Constructor for CopyTraceAction. */ public CopyTraceAction(FailureTraceView view) { super(JUnitMessages.getString("CopyTrace.action.label")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.COPYTRACE_ACTION); fView= view; } /* * @see IAction#run() */ public void run() { String trace= fView.getTrace(); if (trace == null) trace= ""; //$NON-NLS-1$ TextTransfer plainTextTransfer = TextTransfer.getInstance(); Clipboard clipboard= new Clipboard(fView.getComposite().getDisplay()); clipboard.setContents( new String[]{ convertLineTerminators(trace) }, new Transfer[]{ plainTextTransfer }); clipboard.dispose(); } private String convertLineTerminators(String in) { StringWriter stringWriter= new StringWriter(); PrintWriter printWriter= new PrintWriter(stringWriter); StringReader stringReader= new StringReader(in); BufferedReader bufferedReader= new BufferedReader(stringReader); String line; try { while ((line= bufferedReader.readLine()) != null) { printWriter.println(line); } } catch (IOException e) { return in; // return the trace unfiltered } return stringWriter.toString(); } }
31,214
Bug 31214 [Show in] Fails for Package Explorer in non-Java project
- create a simple project P - create a simple file called "x.java" in P - open it with the Default Text Editor - in the editor activate "Show in" and select Package Explorer as target -> nothing happens even if P and "x.java" are visible in the Package Explorer
resolved fixed
7d44cce
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T10:00:44Z
2003-02-07T09: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.DragSourceEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ITreeViewerListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeExpansionEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.core.runtime.IPath; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTarget; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ISetSelectionTarget; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.ui.IPackagesViewPart; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; /** * The ViewPart for the ProjectExplorer. It listens to part activation events. * When selection linking with the editor is enabled the view selection tracks * the active editor page. Similarly when a resource is selected in the packages * view the corresponding editor is activated. */ public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IShowInTarget, IPackagesViewPart, IPropertyChangeListener, IViewPartInputProvider { private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical private static final int HIERARCHICAL_LAYOUT= 0x1; private static final int FLAT_LAYOUT= 0x2; public final static String VIEW_ID= JavaUI.ID_PACKAGES; // Persistance tags. static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$ static final String TAG_ELEMENT= "element"; //$NON-NLS-1$ static final String TAG_PATH= "path"; //$NON-NLS-1$ static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$ static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$ static final String TAG_FILTERS = "filters"; //$NON-NLS-1$ static final String TAG_FILTER = "filter"; //$NON-NLS-1$ static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$ private PackageExplorerContentProvider fContentProvider; private PackageExplorerActionGroup fActionSet; private ProblemTreeViewer fViewer; private Menu fContextMenu; private IMemento fMemento; private ISelectionChangedListener fSelectionListener; private String fWorkingSetName; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; private ITreeViewerListener fExpansionListener= new ITreeViewerListener() { public void treeCollapsed(TreeExpansionEvent event) { } public void treeExpanded(TreeExpansionEvent event) { Object element= event.getElement(); if (element instanceof ICompilationUnit || element instanceof IClassFile) expandMainType(element); } }; private PackageExplorerLabelProvider fLabelProvider; /* (non-Javadoc) * Method declared on IViewPart. */ private boolean fLinkingEnabled; public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; restoreLayoutState(memento); } private void restoreLayoutState(IMemento memento) { Integer state= null; if (memento != null) state= memento.getInteger(TAG_LAYOUT); // If no memento try an restore from preference store if(state == null) { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); state= new Integer(store.getInt(TAG_LAYOUT)); } if (state.intValue() == FLAT_LAYOUT) fIsCurrentLayoutFlat= true; else if (state.intValue() == HIERARCHICAL_LAYOUT) fIsCurrentLayoutFlat= false; else fIsCurrentLayoutFlat= true; } /** * Returns the package explorer part of the active perspective. If * there isn't any package explorer part <code>null</code> is returned. */ public static PackageExplorerPart getFromActivePerspective() { IWorkbenchPage activePage= JavaPlugin.getActivePage(); if (activePage == null) return null; IViewPart view= activePage.findView(VIEW_ID); if (view instanceof PackageExplorerPart) return (PackageExplorerPart)view; return null; } /** * Makes the package explorer part visible in the active perspective. If there * isn't a package explorer part registered <code>null</code> is returned. * Otherwise the opened view part is returned. */ public static PackageExplorerPart openInActivePerspective() { try { return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID); } catch(PartInitException pe) { return null; } } public void dispose() { if (fContextMenu != null && !fContextMenu.isDisposed()) fContextMenu.dispose(); getSite().getPage().removePartListener(fPartListener); JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); if (fViewer != null) fViewer.removeTreeListener(fExpansionListener); if (fActionSet != null) fActionSet.dispose(); super.dispose(); } /** * Implementation of IWorkbenchPart.createPartControl(Composite) */ public void createPartControl(Composite parent) { fViewer= createViewer(parent); fViewer.setUseHashlookup(true); fViewer.setComparer(new PackageExplorerElementComparer()); setProviders(); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getTree()); fViewer.getTree().setMenu(fContextMenu); // Register viewer with site. This must be done before making the actions. IWorkbenchPartSite site= getSite(); site.registerContextMenu(menuMgr, fViewer); site.setSelectionProvider(fViewer); site.getPage().addPartListener(fPartListener); if (fMemento != null) { restoreLinkingEnabled(fMemento); } makeActions(); // call before registering for selection changes // Set input after filter and sorter has been set. This avoids resorting and refiltering. restoreFilterAndSorter(); fViewer.setInput(findInputElement()); initDragAndDrop(); initKeyListener(); fSelectionListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { handleSelectionChanged(event); } }; fViewer.addSelectionChangedListener(fSelectionListener); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { fActionSet.handleDoubleClick(event); } }); fViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { fActionSet.handleOpen(event); } }); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); fViewer.addTreeListener(fExpansionListener); if (fMemento != null) restoreUIState(fMemento); fMemento= null; // Set help for the view JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW); fillActionBars(); updateTitle(); } /** * This viewer ensures that non-leaves in the hierarchical * layout are not removed by any filters. * * @since 2.1 */ private ProblemTreeViewer createViewer(Composite parent) { return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) { /* * @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object) */ protected Object[] getFilteredChildren(Object parent) { List list = new ArrayList(); ViewerFilter[] filters = fViewer.getFilters(); Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent); for (int i = 0; i < children.length; i++) { Object object = children[i]; if (!isEssential(object)) { object = filter(object, parent, filters); if (object != null) { list.add(object); } } else list.add(object); } return list.toArray(); } // Sends the object through the given filters private Object filter(Object object, Object parent, ViewerFilter[] filters) { for (int i = 0; i < filters.length; i++) { ViewerFilter filter = filters[i]; if (!filter.select(fViewer, parent, object)) return null; } return object; } /* Checks if a filtered object in essential (ie. is a parent that * should not be removed). */ private boolean isEssential(Object object) { try { if (!isFlatLayout() && object instanceof IPackageFragment) { IPackageFragment fragment = (IPackageFragment) object; return !fragment.isDefaultPackage() && fragment.hasSubpackages(); } } catch (JavaModelException e) { JavaPlugin.log(e); } return false; } }; } /** * Answers whether this part shows the packages flat or hierarchical. * * @since 2.1 */ boolean isFlatLayout() { return fIsCurrentLayoutFlat; } private void setProviders() { //content provider must be set before the label provider fContentProvider= createContentProvider(); fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setContentProvider(fContentProvider); fLabelProvider= createLabelProvider(); fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false)); // problem decoration provided by PackageLabelProvider } void toggleLayout() { // Update current state and inform content and label providers fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat; saveLayoutState(null); fContentProvider.setIsFlatLayout(isFlatLayout()); fLabelProvider.setIsFlatLayout(isFlatLayout()); fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } /** * This method should only be called inside this class * and from test cases. */ public PackageExplorerContentProvider createContentProvider() { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS)); return new PackageExplorerContentProvider(showCUChildren, reconcile); } private PackageExplorerLabelProvider createLabelProvider() { return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, fContentProvider); } private void fillActionBars() { IActionBars actionBars= getViewSite().getActionBars(); fActionSet.fillActionBars(actionBars); } private Object findInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IWorkspace) { return JavaCore.create(((IWorkspace)input).getRoot()); } else if (input instanceof IContainer) { IJavaElement element= JavaCore.create((IContainer)input); if (element != null && element.exists()) return element; return input; } //1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective // we can't handle the input // fall back to show the workspace return JavaCore.create(JavaPlugin.getWorkspace().getRoot()); } /** * Answer the property defined by key. */ public Object getAdapter(Class key) { if (key.equals(ISelectionProvider.class)) return fViewer; if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(key); } /** * Returns the tool tip text for the given element. */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$ } else { result= path.makeRelative().toString(); } } if (fWorkingSetName == null) return result; String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$ if (result.length() == 0) return wsstr; return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$ } public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } /** * @see IWorkbenchPart#setFocus() */ public void setFocus() { fViewer.getTree().setFocus(); } /** * Returns the current selection. */ private ISelection getSelection() { return fViewer.getSelection(); } //---- Action handling ---------------------------------------------------------- /** * Called when the context menu is about to open. Override * to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); fActionSet.setContext(new ActionContext(getSelection())); fActionSet.fillContextMenu(menu); fActionSet.setContext(null); } private void makeActions() { fActionSet= new PackageExplorerActionGroup(this); } //---- Event handling ---------------------------------------------------------- private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance(), FileTransfer.getInstance()}; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fViewer), new FileTransferDropAdapter(fViewer) }; fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); // Drag Adapter Control control= fViewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fViewer), new ResourceTransferDragAdapter(fViewer), new FileTransferDragAdapter(fViewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners) { public void dragStart(DragSourceEvent event) { IStructuredSelection selection= (IStructuredSelection)getSelection(); if (selection.isEmpty()) { event.doit= false; return; } for (Iterator iter= selection.iterator(); iter.hasNext(); ) { if (iter.next() instanceof IMember) { setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)}); break; } } super.dragStart(event); } }); } /** * Handles selection changed in viewer. * Updates global actions. * Links to editor (if option enabled) */ private void handleSelectionChanged(SelectionChangedEvent event) { IStructuredSelection selection= (IStructuredSelection) event.getSelection(); fActionSet.handleSelectionChanged(event); // if (OpenStrategy.getOpenMethod() != OpenStrategy.SINGLE_CLICK) linkToEditor(selection); } public void selectReveal(ISelection selection) { selectReveal(selection, 0); } private void selectReveal(final ISelection selection, final int count) { Control ctrl= getViewer().getControl(); if (ctrl == null || ctrl.isDisposed()) return; ISelection javaSelection= convertSelection(selection); fViewer.setSelection(javaSelection, true); PackageExplorerContentProvider provider= (PackageExplorerContentProvider)getViewer().getContentProvider(); ISelection cs= fViewer.getSelection(); // If we have Pending changes and the element could not be selected then // we try it again on more time by posting the select and reveal asynchronuoulsy // to the event queue. See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=30700 // for a discussion of the underlying problem. if (count == 0 && provider.hasPendingChanges() && !javaSelection.equals(cs)) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { selectReveal(selection, count + 1); } }); } } private ISelection convertSelection(ISelection s) { if (!(s instanceof IStructuredSelection)) return s; Object[] elements= ((StructuredSelection)s).toArray(); if (!containsResources(elements)) return s; for (int i= 0; i < elements.length; i++) { Object o= elements[i]; if (o instanceof IResource) { IJavaElement jElement= JavaCore.create((IResource)o); if (jElement != null && jElement.exists()) elements[i]= jElement; } } return new StructuredSelection(elements); } private boolean containsResources(Object[] elements) { for (int i = 0; i < elements.length; i++) { if (elements[i] instanceof IResource) return true; } return false; } public void selectAndReveal(Object element) { selectReveal(new StructuredSelection(element)); } boolean isLinkingEnabled() { return fLinkingEnabled; } /** * Initializes the linking enabled setting from the preference store. */ private void initLinkingEnabled() { fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { // ignore selection changes if the package explorer is not the active part. // In this case the selection change isn't triggered by a user. if (!isActivePart()) return; Object obj= selection.getFirstElement(); if (selection.size() == 1) { IEditorPart part= EditorUtility.isOpenInEditor(obj); if (part != null) { IWorkbenchPage page= getSite().getPage(); page.bringToTop(part); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) obj); } } } private boolean isActivePart() { return this == getSite().getPage().getActivePart(); } public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } saveExpansionState(memento); saveSelectionState(memento); saveLayoutState(memento); saveLinkingEnabled(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //saveScrollState(memento, fViewer.getTree()); fActionSet.saveFilterAndSorterState(memento); } private void saveLinkingEnabled(IMemento memento) { memento.putInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, fLinkingEnabled ? 1 : 0); } /** * Saves the current layout state. * * @param memento the memento to save the state into or * <code>null</code> to store the state in the preferences * @since 2.1 */ private void saveLayoutState(IMemento memento) { if (memento != null) { memento.putInteger(TAG_LAYOUT, getLayoutAsInt()); } else { //if memento is null save in preference store IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(TAG_LAYOUT, getLayoutAsInt()); } } private int getLayoutAsInt() { if (fIsCurrentLayoutFlat) return FLAT_LAYOUT; else return HIERARCHICAL_LAYOUT; } protected void saveScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position)); //save horizontal position bar= tree.getHorizontalBar(); position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position)); } protected void saveSelectionState(IMemento memento) { Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray(); if (elements.length > 0) { IMemento selectionMem= memento.createChild(TAG_SELECTION); for (int i= 0; i < elements.length; i++) { IMemento elementMem= selectionMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= elements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier()); } } } protected void saveExpansionState(IMemento memento) { Object expandedElements[]= fViewer.getVisibleExpandedElements(); if (expandedElements.length > 0) { IMemento expandedMem= memento.createChild(TAG_EXPANDED); for (int i= 0; i < expandedElements.length; i++) { IMemento elementMem= expandedMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= expandedElements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier()); } } } private void restoreFilterAndSorter() { fViewer.setSorter(new JavaElementSorter()); if (fMemento != null) fActionSet.restoreFilterAndSorterState(fMemento); } private void restoreUIState(IMemento memento) { restoreExpansionState(memento); restoreSelectionState(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //restoreScrollState(memento, fViewer.getTree()); } private void restoreLinkingEnabled(IMemento memento) { Integer val= memento.getInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); if (val != null) { fLinkingEnabled= val.intValue() != 0; } } protected void restoreScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_VERTICAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore, don't set scrollposition } } bar= tree.getHorizontalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_HORIZONTAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore don't set scroll position } } } protected void restoreSelectionState(IMemento memento) { IMemento childMem; childMem= memento.getChild(TAG_SELECTION); if (childMem != null) { ArrayList list= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) list.add(element); } fViewer.setSelection(new StructuredSelection(list)); } } protected void restoreExpansionState(IMemento memento) { IMemento childMem= memento.getChild(TAG_EXPANDED); if (childMem != null) { ArrayList elements= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) elements.add(element); } fViewer.setExpandedElements(elements.toArray()); } } /** * Create the KeyListener for doing the refresh on the viewer. */ private void initKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { fActionSet.handleKeyEvent(event); } }); } /** * An editor has been activated. Set the selection in this Packages Viewer * to be the editor's input, if linking is enabled. */ void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) return; showInput(getElementOfInput(editor.getEditorInput())); } boolean showInput(Object input) { Object element= null; if (input instanceof IFile) element= JavaCore.create((IFile)input); if (element == null) // try a non Java resource element= input; if (element != null) { ISelection newSelection= new StructuredSelection(element); if (!fViewer.getSelection().equals(newSelection)) { try { fViewer.removeSelectionChangedListener(fSelectionListener); fViewer.setSelection(newSelection); while (element != null && fViewer.getSelection().isEmpty()) { // Try to select parent in case element is filtered element= getParent(element); if (element != null) { newSelection= new StructuredSelection(element); fViewer.setSelection(newSelection); } } } finally { fViewer.addSelectionChangedListener(fSelectionListener); } return true; } } return false; } /** * Returns the element's parent. * * @return the parent or <code>null</code> if there's no parent */ private Object getParent(Object element) { if (element instanceof IJavaElement) return ((IJavaElement)element).getParent(); else if (element instanceof IResource) return ((IResource)element).getParent(); // else if (element instanceof IStorage) { // can't get parent - see bug 22376 // } return null; } /** * A compilation unit or class was expanded, expand * the main type. */ void expandMainType(Object element) { try { IType type= null; if (element instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit)element; IType[] types= cu.getTypes(); if (types.length > 0) type= types[0]; } else if (element instanceof IClassFile) { IClassFile cf= (IClassFile)element; type= cf.getType(); } if (type != null) { final IType type2= type; Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) fViewer.expandToLevel(type2, 1); } }); } } } catch(JavaModelException e) { // no reveal } } /** * Returns the element contained in the EditorInput */ Object getElementOfInput(IEditorInput input) { if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); else if (input instanceof IFileEditorInput) return ((IFileEditorInput)input).getFile(); else if (input instanceof JarEntryEditorInput) return ((JarEntryEditorInput)input).getStorage(); return null; } /** * Returns the Viewer. */ TreeViewer getViewer() { return fViewer; } /** * Returns the TreeViewer. */ public TreeViewer getTreeViewer() { return fViewer; } boolean isExpandable(Object element) { if (fViewer == null) return false; return fViewer.isExpandable(element); } void setWorkingSetName(String workingSetName) { fWorkingSetName= workingSetName; } /** * Updates the title text and title tool tip. * Called whenever the input of the viewer changes. */ void updateTitle() { Object input= fViewer.getInput(); String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ if (input == null || (input instanceof IJavaModel)) { setTitle(viewName); setTitleToolTip(""); //$NON-NLS-1$ } else { String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$ setTitle(title); setTitleToolTip(getToolTipText(input)); } } /** * Sets the decorator for the package explorer. * * @param decorator a label decorator or <code>null</code> for no decorations. * @deprecated To be removed */ public void setLabelDecorator(ILabelDecorator decorator) { } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fViewer == null) return; boolean refreshViewer= false; if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) { fActionSet.updateActionBars(getViewSite().getActionBars()); boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); ((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren); refreshViewer= true; } else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { refreshViewer= true; } if (refreshViewer) fViewer.refresh(); } /* (non-Javadoc) * @see IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { if (fViewer != null) { return fViewer.getInput(); } return null; } public void collapseAll() { fViewer.getControl().setRedraw(false); fViewer.collapseToLevel(getViewPartInput(), TreeViewer.ALL_LEVELS); fViewer.getControl().setRedraw(true); } public PackageExplorerPart() { initLinkingEnabled(); } public boolean show(ShowInContext context) { Object input= context.getInput(); if (input instanceof IEditorInput) return showInput(getElementOfInput((IEditorInput)context.getInput())); ISelection selection= context.getSelection(); if (selection != null) { selectReveal(selection); return true; } return false; } /** * Returns the <code>IShowInSource</code> for this view. */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( getViewer().getInput(), getViewer().getSelection()); } }; } /** * @see IResourceNavigator#setLinkingEnabled(boolean) * @since 2.1 */ public void setLinkingEnabled(boolean enabled) { fLinkingEnabled= enabled; PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, enabled); if (enabled) { IEditorPart editor = getSite().getPage().getActiveEditor(); if (editor != null) { editorActivated(editor); } } } }
20,768
Bug 20768 JUnit New TestCase wizard inserts "[" in method name [JUnit]
For the method (in the class being tested) with the signature "static double[] applyPixelEncoding(double[][] pm, double value[])" and for which another method exists with the same name but different signature, the wizard generates the method in the test class "public void testApplyPixelEncoding[DArrayDArray() {}"
resolved fixed
75f92df
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T13:02:58Z
2002-06-21T00:40:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestCaseCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.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.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.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds; 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.layout.GridData; import org.eclipse.swt.layout.GridLayout; 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.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; /** * 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 MethodStubsSelectionButtonGroup 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 boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(WizardMessages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(WizardMessages.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 */ WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ WizardMessages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ WizardMessages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the initial selection and the 2nd page of the wizard.. */ 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 IType typeInCompUnit= (IType) element.getAncestor(IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { classToTest= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) classToTest= cu.findPrimaryType(); 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(); if (!fFirstTime) fTestClassStatus= testClassChanged(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER) || fieldName.equals(SUPER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } if (fieldName.equals(CONTAINER)) { validateJUnitOnBuildPath(); } } 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(); WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE); } 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(WizardMessages.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= GridData.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(WizardMessages.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= GridData.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(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); if (resultArray != null && resultArray.length > 0) type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Returns the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } /** * Returns the class to be tested. */ public IType getClassToTest() { return fClassToTest; } /** * Sets the name of the class to test. */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /** * @see NewTypeWizardPage#createTypeMembers */ protected void createTypeMembers(IType type, ImportsManager 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, ImportsManager 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 { constr += "public "+getTypeName()+"(String name) {\nsuper(name);\n}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(constr, null, true, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, ImportsManager 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, ImportsManager 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); 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]; String returnType= Signature.toString(method.getReturnType()); String body= WizardMessages.getFormattedString("NewTestClassWizPage.comment.class_to_test", new String[]{returnType, method.getElementName()}); //$NON-NLS-1$ newMethod.append("/*\n * "+body+"("); //$NON-NLS-1$ //$NON-NLS-2$ 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)); if (fPage2.getCreateFinalMethodStubsButtonSelection()) newMethod.append("final "); //$NON-NLS-1$ newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } /** * @see DialogPage#setVisible(boolean) */ 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(); } private void validateJUnitOnBuildPath() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return; IJavaProject jp= root.getJavaProject(); try { if (jp.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) != null) return; } catch (JavaModelException e) { } JUnitStatus status= new JUnitStatus(); status.setError(WizardMessages.getString("NewTestClassWizPage.error.junitNotOnbuildpath")); //$NON-NLS-1$ fContainerStatus= status; } /** * Returns the index of the first method that is a test method, i.e. excluding main, setUp() and tearDown(). * If none of the aforementioned method stubs is created, then 0 is returned. As such method stubs are created, * this counter is incremented. */ public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * @see IDialogPage#createControl(Composite) */ 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().getResource(); if (res == null) return; 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, WizardMessages.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.trim().equals("")) { //$NON-NLS-1$ fSuperClassStatus= new JUnitStatus(); ((JUnitStatus)fSuperClassStatus).setError("Super class name is empty"); //$NON-NLS-1$ return; } if (getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(WizardMessages.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(WizardMessages.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= GridData.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(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(WizardMessages.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(WizardMessages.getFormattedString("NewTestClassWizPage.error.testcase.already_exists", typeName));//$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(WizardMessages.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(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String[] {(type.isInterface())?WizardMessages.getString("Interface"):WizardMessages.getString("Class") , classToTestName})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } fClassToTest= type; } catch (JavaModelException e) { status.setError(WizardMessages.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= jproject.findType(packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= jproject.findType("java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= jproject.findType(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()); } } }
13,170
Bug 13170 Missing description on preference pages
Build 20020409 Java preference pages have a description (ended by .) Java -> Refactoring Java -> Junit don't. They start directly with the preferences. Note: Filed separate PR for Java -> Debug
verified fixed
b04b696
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T14:04:07Z
2002-04-10T09:13:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * Sebastian Davids: [email protected] ******************************************************************************/ package org.eclipse.jdt.internal.junit.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.junit.util.ExceptionHandler; import org.eclipse.jdt.internal.junit.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.ISharedImages; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.ColumnLayoutData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ContentViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchViewerSorter; /** * Preference page for JUnit settings. Supports to define the failure * stack filter patterns. */ public class JUnitPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String DEFAULT_NEW_FILTER_TEXT= ""; //$NON-NLS-1$ private static final Image IMG_CUNIT= JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_CLASS); private static final Image IMG_PKG= JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_PACKAGE); private static String[] fgDefaultFilterPatterns= new String[] { "org.eclipse.jdt.internal.junit.runner.*", //$NON-NLS-1$ "org.eclipse.jdt.internal.junit.ui.*", //$NON-NLS-1$ "junit.framework.TestCase", //$NON-NLS-1$ "junit.framework.TestResult", //$NON-NLS-1$ "junit.framework.TestSuite", //$NON-NLS-1$ "junit.framework.Assert", //$NON-NLS-1$ "java.lang.reflect.Method.invoke" //$NON-NLS-1$ }; // Step filter widgets private CheckboxTableViewer fFilterViewer; private Table fFilterTable; private Button fShowOnErrorCheck; private Button fAddPackageButton; private Button fAddTypeButton; private Button fRemoveFilterButton; private Button fAddFilterButton; private Button fEnableAllButton; private Button fDisableAllButton; private Text fEditorText; private String fInvalidEditorText= null; private TableEditor fTableEditor; private TableItem fNewTableItem; private Filter fNewStackFilter; private Label fTableLabel; private StackFilterContentProvider fStackFilterContentProvider; /** * Model object that represents a single entry in the filter table. */ private class Filter { private String fName; private boolean fChecked; public Filter(String name, boolean checked) { setName(name); setChecked(checked); } public String getName() { return fName; } public void setName(String name) { fName= name; } public boolean isChecked() { return fChecked; } public void setChecked(boolean checked) { fChecked= checked; } public boolean equals(Object o) { if (!(o instanceof Filter)) return false; Filter other= (Filter) o; return (getName().equals(other.getName())); } public int hashCode() { return fName.hashCode(); } } /** * Sorter for the filter table; sorts alphabetically ascending. */ private class FilterViewerSorter extends WorkbenchViewerSorter { public int compare(Viewer viewer, Object e1, Object e2) { ILabelProvider lprov= (ILabelProvider) ((ContentViewer) viewer).getLabelProvider(); String name1= lprov.getText(e1); String name2= lprov.getText(e2); if (name1 == null) name1= ""; //$NON-NLS-1$ if (name2 == null) name2= ""; //$NON-NLS-1$ if (name1.length() > 0 && name2.length() > 0) { char char1= name1.charAt(name1.length() - 1); char char2= name2.charAt(name2.length() - 1); if (char1 == '*' && char1 != char2) return -1; if (char2 == '*' && char2 != char1) return 1; } return name1.compareTo(name2); } } /** * Label provider for Filter model objects */ private class FilterLabelProvider extends LabelProvider implements ITableLabelProvider { public String getColumnText(Object object, int column) { return (column == 0) ? ((Filter) object).getName() : ""; //$NON-NLS-1$ } public String getText(Object element) { return ((Filter) element).getName(); } public Image getColumnImage(Object object, int column) { String name= ((Filter) object).getName(); if (name.endsWith(".*") || name.equals(JUnitMessages.getString("JUnitMainTab.label.defaultpackage"))) { //$NON-NLS-1$ //$NON-NLS-2$ //package return IMG_PKG; } else if ("".equals(name)) { //$NON-NLS-1$ //needed for the in-place editor return null; } else if ((Character.isUpperCase(name.charAt(0))) && (name.indexOf('.') < 0)) { //class in default package return IMG_CUNIT; } else { //fully-qualified class or other filter final int lastDotIndex= name.lastIndexOf('.'); if ((-1 != lastDotIndex) && ((name.length() - 1) != lastDotIndex) && Character.isUpperCase(name.charAt(lastDotIndex + 1))) return IMG_CUNIT; } //other filter return null; } } /** * Content provider for the filter table. Content consists of instances of * Filter. */ private class StackFilterContentProvider implements IStructuredContentProvider { private List fFilters; public StackFilterContentProvider() { List active= createActiveStackFiltersList(); List inactive= createInactiveStackFiltersList(); populateFilters(active, inactive); } public void setDefaults() { fFilterViewer.remove(fFilters.toArray()); List active= createDefaultStackFiltersList(); List inactive= new ArrayList(); populateFilters(active, inactive); } protected void populateFilters(List activeList, List inactiveList) { fFilters= new ArrayList(activeList.size() + inactiveList.size()); populateList(activeList, true); if (inactiveList.size() != 0) populateList(inactiveList, false); } protected void populateList(List list, boolean checked) { Iterator iterator= list.iterator(); while (iterator.hasNext()) { String name= (String) iterator.next(); addFilter(name, checked); } } public Filter addFilter(String name, boolean checked) { Filter filter= new Filter(name, checked); if (!fFilters.contains(filter)) { fFilters.add(filter); fFilterViewer.add(filter); fFilterViewer.setChecked(filter, checked); } updateActions(); return filter; } public void saveFilters() { List active= new ArrayList(fFilters.size()); List inactive= new ArrayList(fFilters.size()); Iterator iterator= fFilters.iterator(); while (iterator.hasNext()) { Filter filter= (Filter) iterator.next(); String name= filter.getName(); if (filter.isChecked()) active.add(name); else inactive.add(name); } String pref= JUnitPreferencePage.serializeList((String[]) active.toArray(new String[active.size()])); getPreferenceStore().setValue(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST, pref); pref= JUnitPreferencePage.serializeList((String[]) inactive.toArray(new String[inactive.size()])); getPreferenceStore().setValue(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST, pref); } public void removeFilters(Object[] filters) { for (int i= (filters.length - 1); i >= 0; --i) { Filter filter= (Filter) filters[i]; fFilters.remove(filter); } fFilterViewer.remove(filters); updateActions(); } public void toggleFilter(Filter filter) { boolean newState= !filter.isChecked(); filter.setChecked(newState); fFilterViewer.setChecked(filter, newState); } public Object[] getElements(Object inputElement) { return fFilters.toArray(); } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {} public void dispose() {} } public JUnitPreferencePage() { super(); setPreferenceStore(JUnitPlugin.getDefault().getPreferenceStore()); } protected Control createContents(Composite parent) { WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.JUNIT_PREFERENCE_PAGE); Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 1; layout.marginHeight= 0; layout.marginWidth= 0; composite.setLayout(layout); GridData data= new GridData(); data.verticalAlignment= GridData.FILL; data.horizontalAlignment= GridData.FILL; composite.setLayoutData(data); createStackFilterPreferences(composite); return composite; } /** * Create a group to contain the step filter related widgetry */ private void createStackFilterPreferences(Composite composite) { Composite container= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; container.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); container.setLayoutData(gd); createShowCheck(container); createFilterTable(container); createStepFilterButtons(container); } private void createShowCheck(Composite composite) { GridData data; fShowOnErrorCheck= new Button(composite, SWT.CHECK); fShowOnErrorCheck.setText(JUnitMessages.getString("JUnitPreferencePage.showcheck.label")); //$NON-NLS-1$ data= new GridData(); data.horizontalAlignment= GridData.FILL; data.horizontalSpan= 2; fShowOnErrorCheck.setLayoutData(data); fShowOnErrorCheck.setSelection(getShowOnErrorOnly()); } private void createFilterTable(Composite container) { fTableLabel= new Label(container, SWT.NONE); fTableLabel.setText(JUnitMessages.getString("JUnitPreferencePage.filter.label")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalSpan= 2; fTableLabel.setLayoutData(gd); fFilterTable= new Table(container, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); gd= new GridData(GridData.FILL_HORIZONTAL); fFilterTable.setLayoutData(gd); TableLayout tableLayout= new TableLayout(); ColumnLayoutData[] columnLayoutData= new ColumnLayoutData[1]; columnLayoutData[0]= new ColumnWeightData(100); tableLayout.addColumnData(columnLayoutData[0]); fFilterTable.setLayout(tableLayout); new TableColumn(fFilterTable, SWT.NONE); fFilterViewer= new CheckboxTableViewer(fFilterTable); fTableEditor= new TableEditor(fFilterTable); fFilterViewer.setLabelProvider(new FilterLabelProvider()); fFilterViewer.setSorter(new FilterViewerSorter()); fStackFilterContentProvider= new StackFilterContentProvider(); fFilterViewer.setContentProvider(fStackFilterContentProvider); // input just needs to be non-null fFilterViewer.setInput(this); gd= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL); fFilterViewer.getTable().setLayoutData(gd); fFilterViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { Filter filter= (Filter) event.getElement(); fStackFilterContentProvider.toggleFilter(filter); } }); fFilterViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { ISelection selection= event.getSelection(); fRemoveFilterButton.setEnabled(!selection.isEmpty()); } }); } private void createStepFilterButtons(Composite container) { Composite buttonContainer= new Composite(container, SWT.NONE); GridData gd= new GridData(GridData.FILL_VERTICAL); buttonContainer.setLayoutData(gd); GridLayout buttonLayout= new GridLayout(); buttonLayout.numColumns= 1; buttonLayout.marginHeight= 0; buttonLayout.marginWidth= 0; buttonContainer.setLayout(buttonLayout); fAddFilterButton= new Button(buttonContainer, SWT.PUSH); fAddFilterButton.setText(JUnitMessages.getString("JUnitPreferencePage.addfilterbutton.label")); //$NON-NLS-1$ fAddFilterButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addfilterbutton.tooltip")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fAddFilterButton.setLayoutData(gd); SWTUtil.setButtonDimensionHint(fAddFilterButton); fAddFilterButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { editFilter(); } }); fAddTypeButton= new Button(buttonContainer, SWT.PUSH); fAddTypeButton.setText(JUnitMessages.getString("JUnitPreferencePage.addtypebutton.label")); //$NON-NLS-1$ fAddTypeButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addtypebutton.tooltip")); //$NON-NLS-1$ gd= getButtonGridData(fAddTypeButton); fAddTypeButton.setLayoutData(gd); SWTUtil.setButtonDimensionHint(fAddTypeButton); fAddTypeButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { addType(); } }); fAddPackageButton= new Button(buttonContainer, SWT.PUSH); fAddPackageButton.setText(JUnitMessages.getString("JUnitPreferencePage.addpackagebutton.label")); //$NON-NLS-1$ fAddPackageButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addpackagebutton.tooltip")); //$NON-NLS-1$ gd= getButtonGridData(fAddPackageButton); fAddPackageButton.setLayoutData(gd); SWTUtil.setButtonDimensionHint(fAddPackageButton); fAddPackageButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { addPackage(); } }); fRemoveFilterButton= new Button(buttonContainer, SWT.PUSH); fRemoveFilterButton.setText(JUnitMessages.getString("JUnitPreferencePage.removefilterbutton.label")); //$NON-NLS-1$ fRemoveFilterButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.removefilterbutton.tooltip")); //$NON-NLS-1$ gd= getButtonGridData(fRemoveFilterButton); fRemoveFilterButton.setLayoutData(gd); SWTUtil.setButtonDimensionHint(fRemoveFilterButton); fRemoveFilterButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { removeFilters(); } }); fRemoveFilterButton.setEnabled(false); fEnableAllButton= new Button(buttonContainer, SWT.PUSH); fEnableAllButton.setText(JUnitMessages.getString("JUnitPreferencePage.enableallbutton.label")); //$NON-NLS-1$ fEnableAllButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.enableallbutton.tooltip")); //$NON-NLS-1$ gd= getButtonGridData(fEnableAllButton); fEnableAllButton.setLayoutData(gd); SWTUtil.setButtonDimensionHint(fEnableAllButton); fEnableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { checkAllFilters(true); } }); fDisableAllButton= new Button(buttonContainer, SWT.PUSH); fDisableAllButton.setText(JUnitMessages.getString("JUnitPreferencePage.disableallbutton.label")); //$NON-NLS-1$ fDisableAllButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.disableallbutton.tooltip")); //$NON-NLS-1$ gd= getButtonGridData(fDisableAllButton); fDisableAllButton.setLayoutData(gd); SWTUtil.setButtonDimensionHint(fDisableAllButton); fDisableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { checkAllFilters(false); } }); } private GridData getButtonGridData(Button button) { GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); int widthHint= convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); gd.widthHint= Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); gd.heightHint= convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); return gd; } public void init(IWorkbench workbench) {} /** * Create a new filter in the table (with the default 'new filter' value), * then open up an in-place editor on it. */ private void editFilter() { // if a previous edit is still in progress, finish it if (fEditorText != null) validateChangeAndCleanup(); fNewStackFilter= fStackFilterContentProvider.addFilter(DEFAULT_NEW_FILTER_TEXT, true); fNewTableItem= fFilterTable.getItem(0); // create & configure Text widget for editor // Fix for bug 1766. Border behavior on for text fields varies per platform. // On Motif, you always get a border, on other platforms, // you don't. Specifying a border on Motif results in the characters // getting pushed down so that only there very tops are visible. Thus, // we have to specify different style constants for the different platforms. int textStyles= SWT.SINGLE | SWT.LEFT; if (!SWT.getPlatform().equals("motif")) //$NON-NLS-1$ textStyles |= SWT.BORDER; fEditorText= new Text(fFilterTable, textStyles); GridData gd= new GridData(GridData.FILL_BOTH); fEditorText.setLayoutData(gd); // set the editor fTableEditor.horizontalAlignment= SWT.LEFT; fTableEditor.grabHorizontal= true; fTableEditor.setEditor(fEditorText, fNewTableItem, 0); // get the editor ready to use fEditorText.setText(fNewStackFilter.getName()); fEditorText.selectAll(); setEditorListeners(fEditorText); fEditorText.setFocus(); } private void setEditorListeners(Text text) { // CR means commit the changes, ESC means abort and don't commit text.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { if (event.character == SWT.CR) { if (fInvalidEditorText != null) { fEditorText.setText(fInvalidEditorText); fInvalidEditorText= null; } else validateChangeAndCleanup(); } else if (event.character == SWT.ESC) { removeNewFilter(); cleanupEditor(); } } }); // Consider loss of focus on the editor to mean the same as CR text.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent event) { if (fInvalidEditorText != null) { fEditorText.setText(fInvalidEditorText); fInvalidEditorText= null; } else validateChangeAndCleanup(); } }); // Consume traversal events from the text widget so that CR doesn't // traverse away to dialog's default button. Without this, hitting // CR in the text field closes the entire dialog. text.addListener(SWT.Traverse, new Listener() { public void handleEvent(Event event) { event.doit= false; } }); } private void validateChangeAndCleanup() { String trimmedValue= fEditorText.getText().trim(); // if the new value is blank, remove the filter if (trimmedValue.length() < 1) removeNewFilter(); // if it's invalid, beep and leave sitting in the editor else if (!validateEditorInput(trimmedValue)) { fInvalidEditorText= trimmedValue; fEditorText.setText(JUnitMessages.getString("JUnitPreferencePage.invalidstepfilterreturnescape")); //$NON-NLS-1$ getShell().getDisplay().beep(); return; // otherwise, commit the new value if not a duplicate } else { Object[] filters= fStackFilterContentProvider.getElements(null); for (int i= 0; i < filters.length; i++) { Filter filter= (Filter) filters[i]; if (filter.getName().equals(trimmedValue)) { removeNewFilter(); cleanupEditor(); return; } } fNewTableItem.setText(trimmedValue); fNewStackFilter.setName(trimmedValue); fFilterViewer.refresh(); } cleanupEditor(); } /** * Cleanup all widgetry & resources used by the in-place editing */ private void cleanupEditor() { if (fEditorText == null) return; fNewStackFilter= null; fNewTableItem= null; fTableEditor.setEditor(null, null, 0); fEditorText.dispose(); fEditorText= null; } private void removeNewFilter() { fStackFilterContentProvider.removeFilters(new Object[] { fNewStackFilter }); } /** * A valid step filter is simply one that is a valid Java identifier. * and, as defined in the JDI spec, the regular expressions used for * step filtering must be limited to exact matches or patterns that * begin with '*' or end with '*'. Beyond this, a string cannot be validated * as corresponding to an existing type or package (and this is probably not * even desirable). */ private boolean validateEditorInput(String trimmedValue) { char firstChar= trimmedValue.charAt(0); if ((!(Character.isJavaIdentifierStart(firstChar)) || (firstChar == '*'))) return false; int length= trimmedValue.length(); for (int i= 1; i < length; i++) { char c= trimmedValue.charAt(i); if (!Character.isJavaIdentifierPart(c)) { if (c == '.' && i != (length - 1)) continue; if (c == '*' && i == (length - 1)) continue; return false; } } return true; } private void addType() { Shell shell= getShell(); SelectionDialog dialog= null; try { dialog= JavaUI.createTypeDialog( shell, new ProgressMonitorDialog(shell), SearchEngine.createWorkspaceScope(), IJavaElementSearchConstants.CONSIDER_CLASSES, false); } catch (JavaModelException jme) { String title= JUnitMessages.getString("JUnitPreferencePage.addtypedialog.title"); //$NON-NLS-1$ String message= JUnitMessages.getString("JUnitPreferencePage.addtypedialog.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(jme, shell, title, message); return; } dialog.setTitle(JUnitMessages.getString("JUnitPreferencePage.addtypedialog.title")); //$NON-NLS-1$ dialog.setMessage(JUnitMessages.getString("JUnitPreferencePage.addtypedialog.message")); //$NON-NLS-1$ if (dialog.open() == IDialogConstants.CANCEL_ID) return; Object[] types= dialog.getResult(); if (types != null && types.length > 0) { IType type= (IType) types[0]; fStackFilterContentProvider.addFilter(type.getFullyQualifiedName(), true); } } private void addPackage() { Shell shell= getShell(); ElementListSelectionDialog dialog= null; try { dialog= JUnitPlugin.createAllPackagesDialog(shell, null, true); } catch (JavaModelException jme) { String title= JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.title"); //$NON-NLS-1$ String message= JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(jme, shell, title, message); return; } dialog.setTitle(JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.title")); //$NON-NLS-1$ dialog.setMessage(JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.message")); //$NON-NLS-1$ dialog.setMultipleSelection(true); if (dialog.open() == IDialogConstants.CANCEL_ID) return; Object[] packages= dialog.getResult(); if (packages == null) return; for (int i= 0; i < packages.length; i++) { IJavaElement pkg= (IJavaElement) packages[i]; String filter= pkg.getElementName(); if (filter.length() < 1) filter= JUnitMessages.getString("JUnitMainTab.label.defaultpackage"); //$NON-NLS-1$ else filter += ".*"; //$NON-NLS-1$ fStackFilterContentProvider.addFilter(filter, true); } } private void removeFilters() { IStructuredSelection selection= (IStructuredSelection) fFilterViewer.getSelection(); fStackFilterContentProvider.removeFilters(selection.toArray()); } private void checkAllFilters(boolean check) { Object[] filters= fStackFilterContentProvider.getElements(null); for (int i= (filters.length - 1); i >= 0; --i) ((Filter) filters[i]).setChecked(check); fFilterViewer.setAllChecked(check); } public boolean performOk() { IPreferenceStore store= getPreferenceStore(); store.setValue(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY, fShowOnErrorCheck.getSelection()); fStackFilterContentProvider.saveFilters(); return true; } protected void performDefaults() { setDefaultValues(); super.performDefaults(); } private void setDefaultValues() { fStackFilterContentProvider.setDefaults(); } /** * Returns the default list of active stack filters. * * @return list */ protected List createDefaultStackFiltersList() { return Arrays.asList(fgDefaultFilterPatterns); } /** * Returns a list of active stack filters. * * @return list */ protected List createActiveStackFiltersList() { return Arrays.asList(getFilterPatterns()); } /** * Returns a list of active stack filters. * * @return list */ protected List createInactiveStackFiltersList() { String[] strings= JUnitPreferencePage.parseList(getPreferenceStore().getString(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST)); return Arrays.asList(strings); } protected void updateActions() { if (fEnableAllButton == null) return; boolean enabled= fFilterViewer.getTable().getItemCount() > 0; fEnableAllButton.setEnabled(enabled); fDisableAllButton.setEnabled(enabled); } public static String[] getFilterPatterns() { IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore(); return JUnitPreferencePage.parseList(store.getString(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST)); } public static boolean getFilterStack() { IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore(); return store.getBoolean(IJUnitPreferencesConstants.DO_FILTER_STACK); } public static void setFilterStack(boolean filter) { IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore(); store.setValue(IJUnitPreferencesConstants.DO_FILTER_STACK, filter); } public static void initializeDefaults(IPreferenceStore store) { store.setDefault(IJUnitPreferencesConstants.DO_FILTER_STACK, true); store.setDefault(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY, false); String list= store.getString(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST); if ("".equals(list)) { //$NON-NLS-1$ String pref= JUnitPreferencePage.serializeList(fgDefaultFilterPatterns); store.setValue(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST, pref); } store.setValue(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST, ""); //$NON-NLS-1$ } public static boolean getShowOnErrorOnly() { IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore(); return store.getBoolean(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY); } /** * Parses the comma separated string into an array of strings * * @return list */ private static String[] parseList(String listString) { List list= new ArrayList(10); StringTokenizer tokenizer= new StringTokenizer(listString, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) list.add(tokenizer.nextToken()); return (String[]) list.toArray(new String[list.size()]); } /** * Serializes the array of strings into one comma * separated string. * * @param list array of strings * @return a single string composed of the given list */ private static String serializeList(String[] list) { if (list == null) return ""; //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(); for (int i= 0; i < list.length; i++) { if (i > 0) buffer.append(','); buffer.append(list[i]); } return buffer.toString(); } }
13,170
Bug 13170 Missing description on preference pages
Build 20020409 Java preference pages have a description (ended by .) Java -> Refactoring Java -> Junit don't. They start directly with the preferences. Note: Filed separate PR for Java -> Debug
verified fixed
b04b696
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T14:04:07Z
2002-04-10T09:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/RefactoringPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.preference.FieldEditorPreferencePage; import org.eclipse.jface.preference.RadioGroupFieldEditor; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; import org.eclipse.jdt.internal.ui.refactoring.RefactoringPreferences; public class RefactoringPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { private static final String FATAL_SEVERITY= PreferenceConstants.REFACTOR_FATAL_SEVERITY; private static final String ERROR_SEVERITY= PreferenceConstants.REFACTOR_ERROR_SEVERITY; private static final String WARNING_SEVERITY= PreferenceConstants.REFACTOR_WARNING_SEVERITY; private static final String INFO_SEVERITY= PreferenceConstants.REFACTOR_INFO_SEVERITY; public RefactoringPreferencePage() { super(GRID); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); } public void createControl(Composite parent) { // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.REFACTORING_PREFERENCE_PAGE); } public void createFieldEditors() { addField(createSeverityLevelField(getFieldEditorParent())); addField(createSaveAllField(getFieldEditorParent())); } private FieldEditor createSeverityLevelField(Composite parent) { RadioGroupFieldEditor editor= new RadioGroupFieldEditor( RefactoringPreferences.PREF_ERROR_PAGE_SEVERITY_THRESHOLD, RefactoringMessages.getString("RefactoringPreferencePage.show_error_page"), //$NON-NLS-1$ 1, new String[] [] { { RefactoringMessages.getString("RefactoringPreferencePage.fatal_error"), FATAL_SEVERITY }, //$NON-NLS-1$ { RefactoringMessages.getString("RefactoringPreferencePage.error"), ERROR_SEVERITY }, //$NON-NLS-1$ { RefactoringMessages.getString("RefactoringPreferencePage.warning"), WARNING_SEVERITY }, //$NON-NLS-1$ { RefactoringMessages.getString("RefactoringPreferencePage.info"), INFO_SEVERITY } //$NON-NLS-1$ }, parent, true ); return editor; } private FieldEditor createSaveAllField(Composite parent) { BooleanFieldEditor editor= new BooleanFieldEditor( RefactoringPreferences.PREF_SAVE_ALL_EDITORS, RefactoringMessages.getString("RefactoringPreferencePage.auto_save"), //$NON-NLS-1$ BooleanFieldEditor.DEFAULT, parent); return editor; } public void init(IWorkbench workbench) { } public boolean performOk() { JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } }
30,543
Bug 30543 [DND] Files deleted when dragged to mozilla
In the Resource or Java perspectives, after dragging an html file from the navigator to be viewed in Mozilla, the file is deleted from the Eclipse views and from the filesystem. Not true of IE 5.5 or Netscape 4.72 on the same machine. Versions: - Eclipse 2.0.2 - NT 4.0 SP6 - Mozilla 1.2.1
resolved fixed
54f2ba5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T14:36:03Z
2003-01-29T22:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/FileTransferDragAdapter.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.packageview; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.corext.util.Resources; /** * Drag support class to allow dragging of files and folder from * the packages view to another application. */ class FileTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener { private ISelectionProvider fProvider; FileTransferDragAdapter(ISelectionProvider provider) { fProvider= provider; Assert.isNotNull(fProvider); } public Transfer getTransfer() { return FileTransfer.getInstance(); } public void dragStart(DragSourceEvent event) { event.doit= isDragable(fProvider.getSelection()); } private boolean isDragable(ISelection selection) { if (selection instanceof IStructuredSelection) { for (Iterator iter= ((IStructuredSelection)selection).iterator(); iter.hasNext();) { Object element= iter.next(); if (element instanceof IPackageFragment) { return false; } else if (element instanceof IJavaElement) { IPackageFragmentRoot root= (IPackageFragmentRoot)((IJavaElement)element).getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (root != null && root.isArchive()) return false; } } return true; } return false; } public void dragSetData(DragSourceEvent event){ List elements= getResources(); if (elements == null || elements.size() == 0) { event.data= null; return; } event.data= getResourceLocations(elements); } private static String[] getResourceLocations(List resources) { return Resources.getLocationOSStrings((IResource[]) resources.toArray(new IResource[resources.size()])); } public void dragFinished(DragSourceEvent event) { if (!event.doit) return; if (event.detail == DND.DROP_MOVE){ handleDropMove(event); } else if (event.detail == DND.DROP_NONE || event.detail == DND.DROP_TARGET_MOVE) { handleRefresh(event); } } private void handleDropMove(DragSourceEvent event) { final List elements= getResources(); if (elements == null || elements.size() == 0) return; WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(IProgressMonitor monitor) throws CoreException { try { monitor.beginTask(PackagesMessages.getString("DragAdapter.deleting"), elements.size()); //$NON-NLS-1$ MultiStatus status= createMultiStatus(); Iterator iter= elements.iterator(); while(iter.hasNext()) { IResource resource= (IResource)iter.next(); try { monitor.subTask(resource.getFullPath().toOSString()); resource.delete(true, null); } catch (CoreException e) { status.add(e.getStatus()); } finally { monitor.worked(1); } } if (!status.isOK()) { throw new CoreException(status); } } finally { monitor.done(); } } }; runOperation(op, true, false); } private void handleRefresh(DragSourceEvent event) { final Set roots= collectRoots(getResources()); WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(IProgressMonitor monitor) throws CoreException { try { monitor.beginTask(PackagesMessages.getString("DragAdapter.refreshing"), roots.size()); //$NON-NLS-1$ MultiStatus status= createMultiStatus(); Iterator iter= roots.iterator(); while (iter.hasNext()) { IResource r= (IResource)iter.next(); try { r.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { status.add(e.getStatus()); } } if (!status.isOK()) { throw new CoreException(status); } } finally { monitor.done(); } } }; runOperation(op, true, false); } protected Set collectRoots(final List elements) { final Set roots= new HashSet(10); Iterator iter= elements.iterator(); while (iter.hasNext()) { IResource resource= (IResource)iter.next(); IResource parent= resource.getParent(); if (parent == null) { roots.add(resource); } else { roots.add(parent); } } return roots; } private List getResources() { ISelection s= fProvider.getSelection(); if (!(s instanceof IStructuredSelection)) return null; List result= new ArrayList(10); Iterator iter= ((IStructuredSelection)s).iterator(); while (iter.hasNext()) { Object o= iter.next(); IResource r= null; if (o instanceof IResource) { r= (IResource)o; } else if (o instanceof IAdaptable) { r= (IResource)((IAdaptable)o).getAdapter(IResource.class); } if (r != null) result.add(r); } return result; } private MultiStatus createMultiStatus() { return new MultiStatus(JavaPlugin.getPluginId(), IStatus.OK, PackagesMessages.getString("DragAdapter.problem"), null); //$NON-NLS-1$ } private void runOperation(IRunnableWithProgress op, boolean fork, boolean cancelable) { try { Shell parent= JavaPlugin.getActiveWorkbenchShell(); new ProgressMonitorDialog(parent).run(fork, cancelable, op); } catch (InvocationTargetException e) { String message= PackagesMessages.getString("DragAdapter.problem"); //$NON-NLS-1$ String title= PackagesMessages.getString("DragAdapter.problemTitle"); //$NON-NLS-1$ ExceptionHandler.handle(e, title, message); } catch (InterruptedException e) { // Do nothing. Operation has been canceled by user. } } }
28,720
Bug 28720 Creating a JUnit TestCase gives an error
Whenever I upgrade Eclipse, I always rename the old version to eclipse.old and install in a new directory called eclipse and then copy in my previous WorkSpace from eclipse.old. Everything works fine except when I try to create a JUnit TestCase. The TestCase itself is created but the wizard puts up an error dialog with title "New" saying: Creation of element failed. Reason: TestFileUtilities [in Working copy] TestFileUtilities.java [in com.teamphone.common.io [in source\java\TPWeb [in TPWeb]]]] does not exist. I have currently got the M4 build and this also happened when I upgraded to M3. The contents of the log are: !SESSION Dec 20, 2002 10:19:24.283 --------------------------------------------- java.version=1.3.1_02 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_GB Command-line arguments: -os win32 -ws win32 -arch x86 -install file:D:/eclipse/ !ENTRY org.eclipse.jdt.junit 4 4 Dec 20, 2002 10:19:24.283 !MESSAGE Error !STACK 1 Java Model Exception: Java Model Status [TestFileUtilities [in [Working copy] TestFileUtilities.java [in com.teamphone.common.io [in source/java/TPWeb [in TPWeb]]]] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:488) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:299) at org.eclipse.jdt.internal.core.JavaElement.getChildren (JavaElement.java:252) at org.eclipse.jdt.internal.core.JavaElement.getChildrenOfType (JavaElement.java:261) at org.eclipse.jdt.internal.core.SourceType.getMethods (SourceType.java:212) at org.eclipse.jdt.internal.junit.wizards.NewTestCaseCreationWizardPage.createTaskM arkers(NewTestCaseCreationWizardPage.java:658) at org.eclipse.jdt.internal.junit.wizards.NewTestCaseCreationWizardPage.createType (NewTestCaseCreationWizardPage.java:652) at org.eclipse.jdt.ui.wizards.NewTypeWizardPage$1.run (NewTypeWizardPage.java:1671) at org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation.execute (WorkspaceModifyDelegatingOperation.java:39) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run (WorkspaceModifyOperation.java:65) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1564) at org.eclipse.ui.actions.WorkspaceModifyOperation.run (WorkspaceModifyOperation.java:79) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:716) at org.eclipse.jdt.internal.junit.wizards.JUnitWizard.finishPage (JUnitWizard.java:45) at org.eclipse.jdt.internal.junit.wizards.NewTestCaseCreationWizard.performFinish (NewTestCaseCreationWizard.java:55) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:308) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:398) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.actions.NewWizardAction.run(NewWizardAction.java:109) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1446) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1429) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) !ENTRY org.eclipse.jdt.core 4 969 Dec 20, 2002 10:19:24.283 !MESSAGE TestFileUtilities [in [Working copy] TestFileUtilities.java [in com.teamphone.common.io [in source/java/TPWeb [in TPWeb]]]] does not exist.
resolved fixed
b48f1c3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T14:42:21Z
2002-12-20T10:26:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/util/JUnitStubUtility.java
/* * Copyright (c) 2002 IBM Corp. All rights reserved. * This file is made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html */ package org.eclipse.jdt.internal.junit.util; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICodeFormatter; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage.ImportsManager; import org.eclipse.swt.SWT; /** * Utility methods for code generation. * TO DO: some methods are duplicated from org.eclipse.jdt.ui */ public class JUnitStubUtility { public static class GenStubSettings extends CodeGenerationSettings { public boolean fCallSuper; public boolean fMethodOverwrites; public boolean fNoBody; public GenStubSettings(CodeGenerationSettings settings) { this.createComments= settings.createComments; this.createNonJavadocComments= settings.createNonJavadocComments; } } /** * Examines a string and returns the first line delimiter found. */ public static String getLineDelimiterUsed(IJavaElement elem) throws JavaModelException { ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null && cu.exists()) { IBuffer buf= cu.getBuffer(); int length= buf.getLength(); for (int i= 0; i < length; i++) { char ch= buf.getChar(i); if (ch == SWT.CR) { if (i + 1 < length) { if (buf.getChar(i + 1) == SWT.LF) { return "\r\n"; //$NON-NLS-1$ } } return "\r"; //$NON-NLS-1$ } else if (ch == SWT.LF) { return "\n"; //$NON-NLS-1$ } } } return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } public static String codeFormat(String sourceString, int initialIndentationLevel, String lineDelim) { ICodeFormatter formatter= ToolFactory.createDefaultCodeFormatter(null); return formatter.format(sourceString, initialIndentationLevel, null, lineDelim); } /** * Generates a stub. Given a template method, a stub with the same signature * will be constructed so it can be added to a type. * @param destTypeName The name of the type to which the method will be added to (Used for the constructor) * @param method A method template (method belongs to different type than the parent) * @param options Options as defined abouve (GENSTUB_*) * @param imports Imports required by the sub are added to the imports structure * @throws JavaModelException */ public static String genStub(String destTypeName, IMethod method, GenStubSettings settings, ImportsManager imports) throws JavaModelException { IType declaringtype= method.getDeclaringType(); StringBuffer buf= new StringBuffer(); String[] paramTypes= method.getParameterTypes(); String[] paramNames= method.getParameterNames(); String[] excTypes= method.getExceptionTypes(); String retTypeSig= method.getReturnType(); int lastParam= paramTypes.length -1; if (settings.createComments) { if (method.isConstructor()) { String desc= "Constructor for " + destTypeName; //$NON-NLS-1$ genJavaDocStub(desc, paramNames, Signature.SIG_VOID, excTypes, buf); } else { // java doc if (settings.fMethodOverwrites) { boolean isDeprecated= Flags.isDeprecated(method.getFlags()); genJavaDocSeeTag(declaringtype.getElementName(), method.getElementName(), paramTypes, settings.createNonJavadocComments, isDeprecated, buf); } else { // generate a default java doc comment String desc= "Method " + method.getElementName(); //$NON-NLS-1$ genJavaDocStub(desc, paramNames, retTypeSig, excTypes, buf); } } } int flags= method.getFlags(); if (Flags.isPublic(flags) || (declaringtype.isInterface() && !settings.fNoBody)) { buf.append("public "); //$NON-NLS-1$ } else if (Flags.isProtected(flags)) { buf.append("protected "); //$NON-NLS-1$ } else if (Flags.isPrivate(flags)) { buf.append("private "); //$NON-NLS-1$ } if (Flags.isSynchronized(flags)) { buf.append("synchronized "); //$NON-NLS-1$ } if (Flags.isVolatile(flags)) { buf.append("volatile "); //$NON-NLS-1$ } if (Flags.isStrictfp(flags)) { buf.append("strictfp "); //$NON-NLS-1$ } if (Flags.isStatic(flags)) { buf.append("static "); //$NON-NLS-1$ } if (method.isConstructor()) { buf.append(destTypeName); } else { String retTypeFrm= Signature.toString(retTypeSig); if (!isBuiltInType(retTypeSig)) { resolveAndAdd(retTypeSig, declaringtype, imports); } buf.append(Signature.getSimpleName(retTypeFrm)); buf.append(' '); buf.append(method.getElementName()); } buf.append('('); for (int i= 0; i <= lastParam; i++) { String paramTypeSig= paramTypes[i]; String paramTypeFrm= Signature.toString(paramTypeSig); if (!isBuiltInType(paramTypeSig)) { resolveAndAdd(paramTypeSig, declaringtype, imports); } buf.append(Signature.getSimpleName(paramTypeFrm)); buf.append(' '); buf.append(paramNames[i]); if (i < lastParam) { buf.append(", "); //$NON-NLS-1$ } } buf.append(')'); int lastExc= excTypes.length - 1; if (lastExc >= 0) { buf.append(" throws "); //$NON-NLS-1$ for (int i= 0; i <= lastExc; i++) { String excTypeSig= excTypes[i]; String excTypeFrm= Signature.toString(excTypeSig); resolveAndAdd(excTypeSig, declaringtype, imports); buf.append(Signature.getSimpleName(excTypeFrm)); if (i < lastExc) { buf.append(", "); //$NON-NLS-1$ } } } if (settings.fNoBody) { buf.append(";\n\n"); //$NON-NLS-1$ } else { buf.append(" {\n\t"); //$NON-NLS-1$ if (!settings.fCallSuper) { if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { buf.append('\t'); if (!isBuiltInType(retTypeSig) || Signature.getArrayCount(retTypeSig) > 0) { buf.append("return null;\n\t"); //$NON-NLS-1$ } else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) { buf.append("return false;\n\t"); //$NON-NLS-1$ } else { buf.append("return 0;\n\t"); //$NON-NLS-1$ } } } else { buf.append('\t'); if (!method.isConstructor()) { if (!Signature.SIG_VOID.equals(retTypeSig)) { buf.append("return "); //$NON-NLS-1$ } buf.append("super."); //$NON-NLS-1$ buf.append(method.getElementName()); } else { buf.append("super"); //$NON-NLS-1$ } buf.append('('); for (int i= 0; i <= lastParam; i++) { buf.append(paramNames[i]); if (i < lastParam) { buf.append(", "); //$NON-NLS-1$ } } buf.append(");\n\t"); //$NON-NLS-1$ } buf.append("}\n\n"); //$NON-NLS-1$ } return buf.toString(); } /** * Generates a default JavaDoc comment stub for a method. */ private static void genJavaDocStub(String descr, String[] paramNames, String retTypeSig, String[] excTypeSigs, StringBuffer buf) { buf.append("/**\n"); //$NON-NLS-1$ buf.append(" * "); buf.append(descr); buf.append(".\n"); //$NON-NLS-2$ //$NON-NLS-1$ for (int i= 0; i < paramNames.length; i++) { buf.append(" * @param "); buf.append(paramNames[i]); buf.append('\n'); //$NON-NLS-1$ } if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { String simpleName= Signature.getSimpleName(Signature.toString(retTypeSig)); buf.append(" * @return "); buf.append(simpleName); buf.append('\n'); //$NON-NLS-1$ } for (int i= 0; i < excTypeSigs.length; i++) { String simpleName= Signature.getSimpleName(Signature.toString(excTypeSigs[i])); buf.append(" * @throws "); buf.append(simpleName); buf.append('\n'); //$NON-NLS-1$ } buf.append(" */\n"); //$NON-NLS-1$ } /** * Generates a '@see' tag to the defined method. */ public static void genJavaDocSeeTag(String declaringTypeName, String methodName, String[] paramTypes, boolean nonJavaDocComment, boolean isDeprecated, StringBuffer buf) { // create a @see link buf.append("/*"); //$NON-NLS-1$ if (!nonJavaDocComment) { buf.append('*'); } buf.append("\n * @see "); //$NON-NLS-1$ buf.append(declaringTypeName); buf.append('#'); buf.append(methodName); buf.append('('); for (int i= 0; i < paramTypes.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(Signature.getSimpleName(Signature.toString(paramTypes[i]))); } buf.append(")\n"); //$NON-NLS-1$ if (isDeprecated) { buf.append(" * @deprecated\n"); //$NON-NLS-1$ } buf.append(" */\n"); //$NON-NLS-1$ } private static boolean isBuiltInType(String typeName) { char first= Signature.getElementType(typeName).charAt(0); return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); } private static void resolveAndAdd(String refTypeSig, IType declaringType, ImportsManager imports) throws JavaModelException { String resolvedTypeName= JavaModelUtil.getResolvedTypeName(refTypeSig, declaringType); if (resolvedTypeName != null) { imports.addImport(resolvedTypeName); } } }
28,720
Bug 28720 Creating a JUnit TestCase gives an error
Whenever I upgrade Eclipse, I always rename the old version to eclipse.old and install in a new directory called eclipse and then copy in my previous WorkSpace from eclipse.old. Everything works fine except when I try to create a JUnit TestCase. The TestCase itself is created but the wizard puts up an error dialog with title "New" saying: Creation of element failed. Reason: TestFileUtilities [in Working copy] TestFileUtilities.java [in com.teamphone.common.io [in source\java\TPWeb [in TPWeb]]]] does not exist. I have currently got the M4 build and this also happened when I upgraded to M3. The contents of the log are: !SESSION Dec 20, 2002 10:19:24.283 --------------------------------------------- java.version=1.3.1_02 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_GB Command-line arguments: -os win32 -ws win32 -arch x86 -install file:D:/eclipse/ !ENTRY org.eclipse.jdt.junit 4 4 Dec 20, 2002 10:19:24.283 !MESSAGE Error !STACK 1 Java Model Exception: Java Model Status [TestFileUtilities [in [Working copy] TestFileUtilities.java [in com.teamphone.common.io [in source/java/TPWeb [in TPWeb]]]] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:488) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:299) at org.eclipse.jdt.internal.core.JavaElement.getChildren (JavaElement.java:252) at org.eclipse.jdt.internal.core.JavaElement.getChildrenOfType (JavaElement.java:261) at org.eclipse.jdt.internal.core.SourceType.getMethods (SourceType.java:212) at org.eclipse.jdt.internal.junit.wizards.NewTestCaseCreationWizardPage.createTaskM arkers(NewTestCaseCreationWizardPage.java:658) at org.eclipse.jdt.internal.junit.wizards.NewTestCaseCreationWizardPage.createType (NewTestCaseCreationWizardPage.java:652) at org.eclipse.jdt.ui.wizards.NewTypeWizardPage$1.run (NewTypeWizardPage.java:1671) at org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation.execute (WorkspaceModifyDelegatingOperation.java:39) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run (WorkspaceModifyOperation.java:65) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1564) at org.eclipse.ui.actions.WorkspaceModifyOperation.run (WorkspaceModifyOperation.java:79) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:716) at org.eclipse.jdt.internal.junit.wizards.JUnitWizard.finishPage (JUnitWizard.java:45) at org.eclipse.jdt.internal.junit.wizards.NewTestCaseCreationWizard.performFinish (NewTestCaseCreationWizard.java:55) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:308) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:398) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.actions.NewWizardAction.run(NewWizardAction.java:109) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1446) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1429) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) !ENTRY org.eclipse.jdt.core 4 969 Dec 20, 2002 10:19:24.283 !MESSAGE TestFileUtilities [in [Working copy] TestFileUtilities.java [in com.teamphone.common.io [in source/java/TPWeb [in TPWeb]]]] does not exist.
resolved fixed
b48f1c3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T14:42:21Z
2002-12-20T10:26:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestCaseCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.wizards; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; 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.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds; 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.layout.GridData; import org.eclipse.swt.layout.GridLayout; 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.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; /** * 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 MethodStubsSelectionButtonGroup 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 boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(WizardMessages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(WizardMessages.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 */ WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ WizardMessages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ WizardMessages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the initial selection and the 2nd page of the wizard.. */ 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 IType typeInCompUnit= (IType) element.getAncestor(IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { classToTest= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) classToTest= cu.findPrimaryType(); 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(); if (!fFirstTime) fTestClassStatus= testClassChanged(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER) || fieldName.equals(SUPER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } if (fieldName.equals(CONTAINER)) { validateJUnitOnBuildPath(); } } 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(); WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE); } 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(WizardMessages.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= GridData.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(WizardMessages.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= GridData.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(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); if (resultArray != null && resultArray.length > 0) type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Returns the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } /** * Returns the class to be tested. */ public IType getClassToTest() { return fClassToTest; } /** * Sets the name of the class to test. */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /** * @see NewTypeWizardPage#createTypeMembers */ protected void createTypeMembers(IType type, ImportsManager 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, ImportsManager 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 { constr += "public "+getTypeName()+"(String name) {\nsuper(name);\n}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(constr, null, true, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, ImportsManager 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, ImportsManager 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); type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length == 0) return; /* find overloaded methods */ IMethod[] allMethodsArray= fPage2.getAllMethods(); List allMethods= new ArrayList(); allMethods.addAll(Arrays.asList(allMethodsArray)); List overloadedMethods= getOveloadedMethods(allMethods); /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ List newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { IMethod method= methods[i]; String elementName= method.getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(method)) { appendMethodComment(newMethod, method); String[] params= method.getParameterTypes(); appendParameterNamesToMethodName(methodName, params); } /* 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(methodName.toString()); if (fPage2.getCreateFinalMethodStubsButtonSelection()) newMethod.append("final "); //$NON-NLS-1$ newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } public void appendParameterNamesToMethodName(StringBuffer methodName, String[] params) { for (int i= 0; i < params.length; i++) { String param= params[i]; methodName.append(Signature.getSimpleName(Signature.toString(Signature.getElementType(param)))); for (int j= 0, arrayCount= Signature.getArrayCount(param); j < arrayCount; j++) { methodName.append("Array"); //$NON-NLS-1$ } } } private void appendMethodComment(StringBuffer newMethod, IMethod method) throws JavaModelException { String returnType= Signature.toString(method.getReturnType()); String body= WizardMessages.getFormattedString("NewTestClassWizPage.comment.class_to_test", new String[]{returnType, method.getElementName()}); //$NON-NLS-1$ newMethod.append("/*\n * "+body+"("); //$NON-NLS-1$ //$NON-NLS-2$ 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$ } private List getOveloadedMethods(List allMethods) { List 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(); } } } return overloadedMethods; } /** * @see DialogPage#setVisible(boolean) */ 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(); } private void validateJUnitOnBuildPath() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return; IJavaProject jp= root.getJavaProject(); try { if (jp.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) != null) return; } catch (JavaModelException e) { } JUnitStatus status= new JUnitStatus(); status.setError(WizardMessages.getString("NewTestClassWizPage.error.junitNotOnbuildpath")); //$NON-NLS-1$ fContainerStatus= status; } /** * Returns the index of the first method that is a test method, i.e. excluding main, setUp() and tearDown(). * If none of the aforementioned method stubs is created, then 0 is returned. As such method stubs are created, * this counter is incremented. */ public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * @see IDialogPage#createControl(Composite) */ 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().getResource(); if (res == null) return; 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, WizardMessages.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.trim().equals("")) { //$NON-NLS-1$ fSuperClassStatus= new JUnitStatus(); ((JUnitStatus)fSuperClassStatus).setError("Super class name is empty"); //$NON-NLS-1$ return; } if (getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(WizardMessages.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(WizardMessages.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= GridData.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(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(WizardMessages.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(WizardMessages.getFormattedString("NewTestClassWizPage.error.testcase.already_exists", typeName));//$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(WizardMessages.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(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String[] {(type.isInterface())?WizardMessages.getString("Interface"):WizardMessages.getString("Class") , classToTestName})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } fClassToTest= type; } catch (JavaModelException e) { status.setError(WizardMessages.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= jproject.findType(packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= jproject.findType("java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= jproject.findType(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()); } } }
18,687
Bug 18687 Surround with try catch - should propose NumberFormatException
Build F2 From EC: Hi all! I'd like to know if the following is a bug or is the normal behaviour of eclipse. 1) type the code below: int t= Integer.parseInt("1234"); 2) select the line typed in the step 1. 3) try to "surround with try/catch". I do this by pressing alt+S T. Eclipse gives the following messsage: No uncaught exceptions are thrown by the selected code. Catch java.lang.RuntimeException ? I think that eclipse should suggest something like: try { .... } catch (NumberFormatException e) { }
resolved fixed
002ed67
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T15:08:33Z
2002-06-03T10:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_out/TestRuntimeException1.java
18,687
Bug 18687 Surround with try catch - should propose NumberFormatException
Build F2 From EC: Hi all! I'd like to know if the following is a bug or is the normal behaviour of eclipse. 1) type the code below: int t= Integer.parseInt("1234"); 2) select the line typed in the step 1. 3) try to "surround with try/catch". I do this by pressing alt+S T. Eclipse gives the following messsage: No uncaught exceptions are thrown by the selected code. Catch java.lang.RuntimeException ? I think that eclipse should suggest something like: try { .... } catch (NumberFormatException e) { }
resolved fixed
002ed67
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T15:08:33Z
2002-06-03T10:26:40Z
org.eclipse.jdt.ui.tests.refactoring/test
18,687
Bug 18687 Surround with try catch - should propose NumberFormatException
Build F2 From EC: Hi all! I'd like to know if the following is a bug or is the normal behaviour of eclipse. 1) type the code below: int t= Integer.parseInt("1234"); 2) select the line typed in the step 1. 3) try to "surround with try/catch". I do this by pressing alt+S T. Eclipse gives the following messsage: No uncaught exceptions are thrown by the selected code. Catch java.lang.RuntimeException ? I think that eclipse should suggest something like: try { .... } catch (NumberFormatException e) { }
resolved fixed
002ed67
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T15:08:33Z
2002-06-03T10:26:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java
18,687
Bug 18687 Surround with try catch - should propose NumberFormatException
Build F2 From EC: Hi all! I'd like to know if the following is a bug or is the normal behaviour of eclipse. 1) type the code below: int t= Integer.parseInt("1234"); 2) select the line typed in the step 1. 3) try to "surround with try/catch". I do this by pressing alt+S T. Eclipse gives the following messsage: No uncaught exceptions are thrown by the selected code. Catch java.lang.RuntimeException ? I think that eclipse should suggest something like: try { .... } catch (NumberFormatException e) { }
resolved fixed
002ed67
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T15:08:33Z
2002-06-03T10:26:40Z
org.eclipse.jdt.ui/core
18,687
Bug 18687 Surround with try catch - should propose NumberFormatException
Build F2 From EC: Hi all! I'd like to know if the following is a bug or is the normal behaviour of eclipse. 1) type the code below: int t= Integer.parseInt("1234"); 2) select the line typed in the step 1. 3) try to "surround with try/catch". I do this by pressing alt+S T. Eclipse gives the following messsage: No uncaught exceptions are thrown by the selected code. Catch java.lang.RuntimeException ? I think that eclipse should suggest something like: try { .... } catch (NumberFormatException e) { }
resolved fixed
002ed67
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T15:08:33Z
2002-06-03T10:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java
31,119
Bug 31119 Build Path dialog opened for wrong project if element from external JAR is selected [build path]
Build I20030206 Build Path dialog opened for wrong project if element from external JAR is selected 0815 problem with parents of elements from external JARs.
resolved fixed
3f6cb35
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T15:24:11Z
2003-02-06T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OpenBuildPathDialogAction.java
/******************************************************************************* * Copyright (c) 2003 International Business Machines Corp. and others. All * rights reserved. This program and the accompanying materials are made * available under the terms of the Common Public License v1.0 which accompanies * this distribution, and is available at http://www.eclipse.org/legal/cpl-v10. * html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.actions; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.resources.IResource; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.dialogs.BuildPathDialog; public class OpenBuildPathDialogAction implements IWorkbenchWindowActionDelegate { private IWorkbenchWindow fWindow; private IJavaProject fProject; public void dispose() { } public void init(IWorkbenchWindow window) { fWindow= window; } public void run(IAction action) { BuildPathDialog dialog= new BuildPathDialog(fWindow.getShell(), fProject); dialog.open(); } public void selectionChanged(IAction action, ISelection selection) { boolean enable= false; if (selection instanceof IStructuredSelection) { IStructuredSelection s= (IStructuredSelection)selection; if (s.size() == 1) { Object element= s.getFirstElement(); if (element instanceof IJavaElement) { fProject= (IJavaProject)((IJavaElement)element).getAncestor(IJavaElement.JAVA_PROJECT); enable= fProject != null; } else if (element instanceof IAdaptable) { IResource resource= (IResource)((IAdaptable)element).getAdapter(IResource.class); if (resource != null) { IJavaProject p= JavaCore.create(resource.getProject()); if (p.exists()) { fProject= p; enable= true; } } } } } else if (selection instanceof ITextSelection) { IWorkbenchPage activePage= fWindow.getActivePage(); if (activePage != null) { IEditorPart part= activePage.getActiveEditor(); if (part != null) { IEditorInput input= part.getEditorInput(); if (input instanceof IFileEditorInput) { IJavaProject p= JavaCore.create(((IFileEditorInput)input).getFile().getProject()); if (p.exists()) { fProject= p; enable= true; } } } } } action.setEnabled(enable); } }
14,305
Bug 14305 JUnit - TestSuite should not include Abstract classes
I refactored my testcases to use some abstract classes. When I now recreate the testsuite (BTW, this only works in the Java but not in the Java-Browsing perspective), the abstract classes are added. I'm using M5.
resolved fixed
3f26634
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T16:01:54Z
2002-04-22T10:06:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestSuiteCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.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.junit.ui.IJUnitHelpContextIds; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.ExceptionHandler; 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.SWTUtil; 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.IDialogSettings; 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; import org.eclipse.ui.help.WorkbenchHelp; /** * 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$ 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$ public static final String START_MARKER= "//$JUnit-BEGIN$"; //$NON-NLS-1$ public static final String END_MARKER= "//$JUnit-END$"; //$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 MethodStubsSelectionButtonGroup fMethodStubsButtons; private boolean fUpdatedExistingClassButton; protected IStatus fClassesInSuiteStatus; protected IStatus fSuiteNameStatus; public NewTestSuiteCreationWizardPage() { super(true, PAGE_NAME); fSuiteNameStatus= new JUnitStatus(); fSuiteNameTextInitialValue= ""; //$NON-NLS-1$ setTitle(WizardMessages.getString("NewTestSuiteWizPage.title")); //$NON-NLS-1$ setDescription(WizardMessages.getString("NewTestSuiteWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ }; fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage2.method.Stub.label")); //$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); createMethodStubSelectionControls(composite, nColumns); setControl(composite); restoreWidgetValues(); WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTSUITE_WIZARD_PAGE); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } /** * Should be called from the wizard with the initial selection. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); doStatusUpdate(); fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text } /** * @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(); fSuiteNameStatus= testSuiteChanged(); //must check this one too 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 most severe status will be displayed and the ok button enabled/disabled. updateStatus(status); } /** * @see DialogPage#setVisible(boolean) */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { setFocus(); updateClassesInSuiteTable(); handleAllFieldsChanged(); } } private void handleAllFieldsChanged() { handleFieldChanged(PACKAGE); handleFieldChanged(CONTAINER); handleFieldChanged(CLASSES_IN_SUITE); handleFieldChanged(SUITE_NAME); } 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(WizardMessages.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= 80; 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(WizardMessages.getString("NewTestSuiteWizPage.selectAll")); //$NON-NLS-1$ GridData bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); bgd.heightHint = SWTUtil.getButtonHeigthHint(fSelectAllButton); bgd.widthHint = SWTUtil.getButtonWidthHint(fSelectAllButton); 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(WizardMessages.getString("NewTestSuiteWizPage.deselectAll")); //$NON-NLS-1$ bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); bgd.heightHint = SWTUtil.getButtonHeigthHint(fDeselectAllButton); bgd.widthHint = SWTUtil.getButtonWidthHint(fDeselectAllButton); 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 { public ClassesInSuitContentProvider() { super(); } public Object[] getElements(Object parent) { try { if (parent instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) parent; if (pack.exists()) { 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, ImportsManager imports, IProgressMonitor monitor) throws CoreException { writeImports(imports); if (fMethodStubsButtons.isEnabled() && fMethodStubsButtons.isSelected(0)) createMain(type); type.createMethod(getSuiteMethodString(), null, false, null); } protected void createMain(IType type) throws JavaModelException { type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null); } /** * Returns the string content for creating a new suite() method. */ 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(); } /** * Returns the new code to be included in a new suite() or which replaces old code in an existing suite(). */ public static String getUpdatableString(Object[] selectedClasses) throws JavaModelException { StringBuffer suite= new StringBuffer(); suite.append(START_MARKER+"\n"); //$NON-NLS-1$ for (int i= 0; i < selectedClasses.length; i++) { if (selectedClasses[i] instanceof IType) { IType testType= (IType) selectedClasses[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"+END_MARKER); //$NON-NLS-1$ return suite.toString(); } private String getUpdatableString() throws JavaModelException { return getUpdatableString(fClassesInSuiteTable.getCheckedElements()); } /** * Runnable for replacing an existing suite() method. */ 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; } if (! UpdateTestSuite.checkValidateEditStatus(cu, getShell())) return; IType suiteType= cu.getType(getTypeName()); monitor.beginTask(WizardMessages.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(START_MARKER) --> int start= source.indexOf(START_MARKER); int start= source.toString().indexOf(START_MARKER); if (start > -1) { //using JDK 1.4 //int end= source.toString().indexOf(END_MARKER, start) --> int end= source.indexOf(END_MARKER, start) int end= source.toString().indexOf(END_MARKER, start); if (end > -1) { monitor.subTask(WizardMessages.getString("NewTestSuiteWizPage.createType.updating.suite_method")); //$NON-NLS-1$ monitor.worked(1); end += END_MARKER.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(), WizardMessages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.title"), WizardMessages.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) { String title= WizardMessages.getString("NewTestSuiteWizPage.error_tile"); //$NON-NLS-1$ String message= WizardMessages.getString("NewTestSuiteWizPage.error_message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } } /** * Returns true iff an existing suite() method has been replaced. */ public boolean hasUpdatedExistingClass() { return fUpdatedExistingClassButton; } private IStatus classesInSuiteChanged() { JUnitStatus status= new JUnitStatus(); if (fClassesInSuiteTable.getCheckedElements().length <= 0) status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.classes_in_suite.error.no_testclasses_selected")); //$NON-NLS-1$ return status; } private void updateSelectedClassesLabel() { int noOfClassesChecked= fClassesInSuiteTable.getCheckedElements().length; String key= (noOfClassesChecked==1) ? "NewTestClassWizPage.treeCaption.classSelected" : "NewTestClassWizPage.treeCaption.classesSelected"; //$NON-NLS-1$ //$NON-NLS-2$ fSelectedClassesLabel.setText(WizardMessages.getFormattedString(key, new Integer(noOfClassesChecked))); } protected void createSuiteNameControl(Composite composite, int nColumns) { fSuiteNameLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fSuiteNameLabel.setFont(composite.getFont()); fSuiteNameLabel.setText(WizardMessages.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= GridData.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(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } JUnitStatus recursiveSuiteInclusionStatus= checkRecursiveTestSuiteInclusion(); if (! recursiveSuiteInclusionStatus.isOK()) return recursiveSuiteInclusionStatus; IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.typeName.warning.already_exists")); //$NON-NLS-1$ fMethodStubsButtons.setEnabled(false); return status; } } fMethodStubsButtons.setEnabled(true); return status; } private JUnitStatus checkRecursiveTestSuiteInclusion(){ if (fClassesInSuiteTable == null) return new JUnitStatus(); String typeName= getTypeName(); JUnitStatus status= new JUnitStatus(); Object[] checkedClasses= fClassesInSuiteTable.getCheckedElements(); for (int i= 0; i < checkedClasses.length; i++) { IType checkedClass= (IType)checkedClasses[i]; if (checkedClass.getElementName().equals(typeName)){ status.setWarning(WizardMessages.getString("NewTestSuiteCreationWizardPage.infinite_recursion")); //$NON-NLS-1$ return status; } } return new JUnitStatus(); } /** * Sets the focus. */ protected void setFocus() { fSuiteNameText.setFocus(); } /** * Sets the classes in <code>elements</code> as checked. */ public void setCheckedElements(Object[] elements) { fClassesInSuiteTable.setCheckedElements(elements); } protected void cannotUpdateSuiteError() { MessageDialog.openError(getShell(), WizardMessages.getString("NewTestSuiteWizPage.cannotUpdateDialog.title"), //$NON-NLS-1$ WizardMessages.getFormattedString("NewTestSuiteWizPage.cannotUpdateDialog.message", new String[] {START_MARKER, END_MARKER})); //$NON-NLS-1$ } private void writeImports(ImportsManager imports) { imports.addImport("junit.framework.Test"); //$NON-NLS-1$ imports.addImport("junit.framework.TestSuite"); //$NON-NLS-1$ } /** * 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)); //The next 2 lines are necessary. Otherwise, if fMethodsStubsButtons is disabled, and USE_TESTRUNNER gets enabled, //then the checkbox for USE_TESTRUNNER will be the only enabled component of fMethodsStubsButton fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled()); fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled()); 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()); } } }
32,299
Bug 32299 No quick fix for uncaught exception
I have the following method where the call to execute(Runnable) throws an Exception. The code does not compile with: Kind Status Priority Description Resource In Folder Location Error Unhandled exception type EmptyThreadPoolException MQCommunicationManager.java Transidiom- DevE/Java/Source/com/seagullsw/appinterface/server/comm/ibmmq line 129 which is good but there is no quick fix to wrap the call with a try catch block: "No corrections available". protected void processNextInputQueueMessage() { final MQMessage inputMessage = this.readNextInputQueueMessage (); if ((this.isStopFlagUp()) || (inputMessage == null)) { return; } final String request = this.getStringMessage(inputMessage); if (request != null) { this.getAIS().execute(new Runnable() { public void run() { String response = MQCommunicationManager.this.execute(request, inputMessage); if (response != null) { MQCommunicationManager.this.putMessageOnQ(response, MQCommunicationManager.this.getOutputQueue(), inputMessage); } } }); } } Version: 2.1 Build id: 200302061700
resolved fixed
237b14c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T16:10:44Z
2003-02-19T21:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaSelectMarkerRulerAction.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.javaeditor; import java.util.Iterator; import java.util.ResourceBundle; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorExtension; import org.eclipse.ui.texteditor.SelectMarkerRulerAction; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor; /** * A special select marker ruler action which activates quick fix if clicked on a quick fixable problem. */ public class JavaSelectMarkerRulerAction extends SelectMarkerRulerAction { private ITextEditor fMyTextEditor; private Position fPosition; public JavaSelectMarkerRulerAction(ResourceBundle bundle, String prefix, ITextEditor editor, IVerticalRulerInfo ruler) { super(bundle, prefix, editor, ruler); fMyTextEditor= editor; } public void run() { superCall: { if (fPosition == null) break superCall; ITextOperationTarget operation= (ITextOperationTarget) fMyTextEditor.getAdapter(ITextOperationTarget.class); final int opCode= CompilationUnitEditor.CORRECTIONASSIST_PROPOSALS; if (operation == null || !operation.canDoOperation(opCode)) { break superCall; } fMyTextEditor.selectAndReveal(fPosition.getOffset(), fPosition.getLength()); operation.doOperation(opCode); return; } super.run(); } public void update() { // Begin Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=20114 if (!(fMyTextEditor instanceof ITextEditorExtension) || ((ITextEditorExtension) fMyTextEditor).isEditorInputReadOnly()) { fPosition= null; super.update(); return; } // End Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=20114 fPosition= getJavaAnnotationPosition(); if (fPosition != null) setEnabled(true); else super.update(); } private Position getJavaAnnotationPosition() { AbstractMarkerAnnotationModel model= getAnnotationModel(); IDocument document= getDocument(); if (model == null) return null; Iterator iter= model.getAnnotationIterator(); while (iter.hasNext()) { Annotation annotation= (Annotation) iter.next(); if (annotation instanceof IJavaAnnotation) { IJavaAnnotation javaAnnotation= (IJavaAnnotation)annotation; if (javaAnnotation.isRelevant()) { Position position= model.getPosition(annotation); if (includesRulerLine(position, document) && JavaCorrectionProcessor.hasCorrections(javaAnnotation)) return position; } } } return null; } }
14,426
Bug 14426 junit: status line on finish could give more details
time is less interesting than numbers of failures and errors
resolved fixed
a67a465
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T16:25:42Z
2002-04-23T16:40:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * Julien Ruaux: [email protected] * Vincent Massol: [email protected] ******************************************************************************/ package org.eclipse.jdt.internal.junit.ui; import java.net.MalformedURLException; import java.text.NumberFormat; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Vector; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration; import org.eclipse.jdt.junit.ITestRunListener; /** * A ViewPart that shows the results of a test run. */ public class TestRunnerViewPart extends ViewPart implements ITestRunListener2, IPropertyChangeListener { public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$ /** * Number of executed tests during a test run */ protected int fExecutedTests; /** * Number of errors during this test run */ protected int fErrors; /** * Number of failures during this test run */ protected int fFailures; /** * Number of tests run */ private int fTestCount; /** * Map storing TestInfos for each executed test keyed by * the test name. */ private Map fTestInfos = new HashMap(); /** * The first failure of a test run. Used to reveal the * first failed tests at the end of a run. */ private TestRunInfo fFirstFailure; private JUnitProgressBar fProgressBar; private ProgressImages fProgressImages; private Image fViewImage; private CounterPanel fCounterPanel; private boolean fShowOnErrorOnly= false; /** * The view that shows the stack trace of a failure */ private FailureTraceView fFailureView; /** * The collection of ITestRunViews */ private Vector fTestRunViews = new Vector(); /** * The currently active run view */ private ITestRunView fActiveRunView; /** * Is the UI disposed */ private boolean fIsDisposed= false; /** * The launched project */ private IJavaProject fTestProject; /** * The launcher that has started the test */ private String fLaunchMode; private ILaunch fLastLaunch= null; /** * The client side of the remote test runner */ private RemoteTestRunnerClient fTestRunnerClient; final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$ final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$ final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$ final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$ final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$ Image fOriginalViewImage= null; IElementChangedListener fDirtyListener= null; private class StopAction extends Action{ public StopAction() { setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$ setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$ setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$ setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$ setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$ } public void run() { stopTest(); } } private class RerunLastAction extends Action{ public RerunLastAction() { setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$ setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$ setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$ setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$ setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$ } public void run(){ rerunTestRun(); } } /** * Listen for for modifications to Java elements */ private class DirtyListener implements IElementChangedListener { public void elementChanged(ElementChangedEvent event) { processDelta(event.getDelta()); } private boolean processDelta(IJavaElementDelta delta) { int kind= delta.getKind(); int details= delta.getFlags(); int type= delta.getElement().getElementType(); switch (type) { // Consider containers for class files. case IJavaElement.JAVA_MODEL: case IJavaElement.JAVA_PROJECT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: // If we did some different than changing a child we flush the the undo / redo stack. if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) { codeHasChanged(); return false; } break; case IJavaElement.COMPILATION_UNIT: ICompilationUnit unit= (ICompilationUnit)delta.getElement(); // If we change a working copy we do nothing if (unit.isWorkingCopy()) { // Don't examine children of a working copy but keep processing siblings. return true; } else { codeHasChanged(); return false; } case IJavaElement.CLASS_FILE: // Don't examine children of a class file but keep on examining siblings. return true; default: codeHasChanged(); return false; } IJavaElementDelta[] affectedChildren= delta.getAffectedChildren(); if (affectedChildren == null) return true; for (int i= 0; i < affectedChildren.length; i++) { if (!processDelta(affectedChildren[i])) return false; } return true; } } /** * Stops the currently running test and shuts down the RemoteTestRunner */ public void stopTest() { if (fTestRunnerClient != null) fTestRunnerClient.stopTest(); } /** * Stops the currently running test and shuts down the RemoteTestRunner */ public void rerunTestRun() { if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) { try { DebugUITools.saveAndBuildBeforeLaunch(); fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null); } catch (CoreException e) { ErrorDialog.openError(getSite().getShell(), JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$ ); } } } /* * @see ITestRunListener#testRunStarted(testCount) */ public void testRunStarted(final int testCount){ reset(testCount); fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly(); fExecutedTests++; } /* * @see ITestRunListener#testRunEnded */ public void testRunEnded(long elapsedTime){ fExecutedTests--; String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$ postInfo(msg); postAsyncRunnable(new Runnable() { public void run() { if(isDisposed()) return; if (fFirstFailure != null) { fActiveRunView.setSelectedTest(fFirstFailure.fTestName); handleTestSelected(fFirstFailure.fTestName); } updateViewIcon(); if (fDirtyListener == null) { fDirtyListener= new DirtyListener(); JavaCore.addElementChangedListener(fDirtyListener); } } }); } private void updateViewIcon() { if (fErrors+fFailures > 0) fViewImage= fTestRunFailIcon; else fViewImage= fTestRunOKIcon; firePropertyChange(IWorkbenchPart.PROP_TITLE); } private String elapsedTimeAsString(long runTime) { return NumberFormat.getInstance().format((double)runTime/1000); } /* * @see ITestRunListener#testRunStopped */ public void testRunStopped(final long elapsedTime) { String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$ postInfo(msg); postAsyncRunnable(new Runnable() { public void run() { if(isDisposed()) return; resetViewIcon(); } }); } private void resetViewIcon() { fViewImage= fOriginalViewImage; firePropertyChange(IWorkbenchPart.PROP_TITLE); } /* * @see ITestRunListener#testRunTerminated */ public void testRunTerminated() { String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$ showMessage(msg); } private void showMessage(String msg) { showInformation(msg); postError(msg); } /* * @see ITestRunListener#testStarted */ public void testStarted(String testName) { // reveal the part when the first test starts if (!fShowOnErrorOnly && fExecutedTests == 1) postShowTestResultsView(); postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$ TestRunInfo testInfo= getTestInfo(testName); if (testInfo == null) fTestInfos.put(testName, new TestRunInfo(testName)); } /* * @see ITestRunListener#testEnded */ public void testEnded(String testName){ postEndTest(testName); fExecutedTests++; } /* * @see ITestRunListener#testFailed */ public void testFailed(int status, String testName, String trace){ TestRunInfo testInfo= getTestInfo(testName); if (testInfo == null) { testInfo= new TestRunInfo(testName); fTestInfos.put(testName, testInfo); } testInfo.fTrace= trace; testInfo.fStatus= status; if (status == ITestRunListener.STATUS_ERROR) fErrors++; else fFailures++; if (fFirstFailure == null) fFirstFailure= testInfo; // show the view on the first error only if (fShowOnErrorOnly && (fErrors + fFailures == 1)) postShowTestResultsView(); } /* * @see ITestRunListener#testReran */ public void testReran(String className, String testName, int status, String trace) { if (status == ITestRunListener.STATUS_ERROR) { String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$ postError(msg); } else if (status == ITestRunListener.STATUS_FAILURE) { String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$ postError(msg); } else { String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$ postInfo(msg); } String test= testName+"("+className+")"; //$NON-NLS-1$ //$NON-NLS-2$ TestRunInfo info= getTestInfo(test); updateTest(info, status); if (info.fTrace == null || !info.fTrace.equals(trace)) { info.fTrace= trace; showFailure(info.fTrace); } } private void updateTest(TestRunInfo info, final int status) { if (status == info.fStatus) return; if (info.fStatus == ITestRunListener.STATUS_OK) { if (status == ITestRunListener.STATUS_FAILURE) fFailures++; else if (status == ITestRunListener.STATUS_ERROR) fErrors++; } else if (info.fStatus == ITestRunListener.STATUS_ERROR) { if (status == ITestRunListener.STATUS_OK) fErrors--; else if (status == ITestRunListener.STATUS_FAILURE) { fErrors--; fFailures++; } } else if (info.fStatus == ITestRunListener.STATUS_FAILURE) { if (status == ITestRunListener.STATUS_OK) fFailures--; else if (status == ITestRunListener.STATUS_ERROR) { fFailures--; fErrors++; } } info.fStatus= status; final TestRunInfo finalInfo= info; postAsyncRunnable(new Runnable() { public void run() { refreshCounters(); for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) { ITestRunView v= (ITestRunView) e.nextElement(); v.testStatusChanged(finalInfo); } } }); } /* * @see ITestRunListener#testTreeEntry */ public void testTreeEntry(final String treeEntry){ postSyncRunnable(new Runnable() { public void run() { if(isDisposed()) return; for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) { ITestRunView v= (ITestRunView) e.nextElement(); v.newTreeEntry(treeEntry); } } }); } public void startTestRunListening(IJavaElement type, int port, ILaunch launch) { fTestProject= type.getJavaProject(); fLaunchMode= launch.getLaunchMode(); aboutToLaunch(); if (fTestRunnerClient != null) { stopTest(); } fTestRunnerClient= new RemoteTestRunnerClient(); // add the TestRunnerViewPart to the list of registered listeners Vector listeners= JUnitPlugin.getDefault().getTestRunListeners(); ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1]; listeners.copyInto(listenerArray); System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1); listenerArray[0]= this; fTestRunnerClient.startListening(listenerArray, port); fLastLaunch= launch; String title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$ setTitle(title); if (type instanceof IType) setTitleToolTip(((IType)type).getFullyQualifiedName()); else setTitleToolTip(type.getElementName()); } private void aboutToLaunch() { String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$ showInformation(msg); postInfo(msg); fViewImage= fOriginalViewImage; firePropertyChange(IWorkbenchPart.PROP_TITLE); } public void rerunTest(String className, String testName) { DebugUITools.saveAndBuildBeforeLaunch(); if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode)) fTestRunnerClient.rerunTest(className, testName); else if (fLastLaunch != null) { // run the selected test using the previous launch configuration ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration(); if (launchConfiguration != null) { try { ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$ tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName); tmp.launch(fLastLaunch.getLaunchMode(), null); return; } catch (CoreException e) { ErrorDialog.openError(getSite().getShell(), JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$ ); } } MessageDialog.openInformation(getSite().getShell(), JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$ JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$ ); } } public synchronized void dispose(){ fIsDisposed= true; stopTest(); if (fProgressImages != null) fProgressImages.dispose(); JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); fTestRunOKIcon.dispose(); fTestRunFailIcon.dispose(); fStackViewIcon.dispose(); fTestRunOKDirtyIcon.dispose(); fTestRunFailDirtyIcon.dispose(); } private void start(final int total) { resetProgressBar(total); fCounterPanel.setTotal(total); fCounterPanel.setRunValue(0); } private void resetProgressBar(final int total) { fProgressBar.reset(); fProgressBar.setMaximum(total); } private void postSyncRunnable(Runnable r) { if (!isDisposed()) getDisplay().syncExec(r); } private void postAsyncRunnable(Runnable r) { if (!isDisposed()) getDisplay().syncExec(r); } private void aboutToStart() { postSyncRunnable(new Runnable() { public void run() { if (!isDisposed()) { for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) { ITestRunView v= (ITestRunView) e.nextElement(); v.aboutToStart(); } } } }); } private void postEndTest(final String testName) { postSyncRunnable(new Runnable() { public void run() { if(isDisposed()) return; handleEndTest(); for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) { ITestRunView v= (ITestRunView) e.nextElement(); v.endTest(testName); } } }); } private void handleEndTest() { refreshCounters(); fProgressBar.step(fFailures+fErrors); if (fShowOnErrorOnly) { Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrors, fFailures); if (progress != fViewImage) { fViewImage= progress; firePropertyChange(IWorkbenchPart.PROP_TITLE); } } } private void refreshCounters() { fCounterPanel.setErrorValue(fErrors); fCounterPanel.setFailureValue(fFailures); fCounterPanel.setRunValue(fExecutedTests); } protected void postShowTestResultsView() { postAsyncRunnable(new Runnable() { public void run() { if (isDisposed()) return; showTestResultsView(); } }); } public void showTestResultsView() { IWorkbenchWindow window= getSite().getWorkbenchWindow(); IWorkbenchPage page= window.getActivePage(); TestRunnerViewPart testRunner= null; if (page != null) { try { // show the result view testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME); if(testRunner == null) { IWorkbenchPart activePart= page.getActivePart(); testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME); //restore focus stolen by the creation of the console page.activate(activePart); } else { page.bringToTop(testRunner); } } catch (PartInitException pie) { JUnitPlugin.log(pie); } } } protected void postInfo(final String message) { postAsyncRunnable(new Runnable() { public void run() { if (isDisposed()) return; getStatusLine().setErrorMessage(null); getStatusLine().setMessage(message); } }); } protected void postError(final String message) { postAsyncRunnable(new Runnable() { public void run() { if (isDisposed()) return; getStatusLine().setMessage(null); getStatusLine().setErrorMessage(message); } }); } protected void showInformation(final String info){ postSyncRunnable(new Runnable() { public void run() { if (!isDisposed()) fFailureView.setInformation(info); } }); } private CTabFolder createTestRunViews(Composite parent) { CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP); tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL)); ITestRunView failureRunView= new FailureRunView(tabFolder, this); ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this); fTestRunViews.addElement(failureRunView); fTestRunViews.addElement(testHierarchyRunView); tabFolder.setSelection(0); fActiveRunView= (ITestRunView)fTestRunViews.firstElement(); tabFolder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { testViewChanged(event); } }); return tabFolder; } private void testViewChanged(SelectionEvent event) { for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) { ITestRunView v= (ITestRunView) e.nextElement(); if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){ v.setSelectedTest(fActiveRunView.getTestName()); fActiveRunView= v; fActiveRunView.activate(); } } } private SashForm createSashForm(Composite parent) { SashForm sashForm= new SashForm(parent, SWT.VERTICAL); ViewForm top= new ViewForm(sashForm, SWT.NONE); CTabFolder tabFolder= createTestRunViews(top); tabFolder.setLayoutData(new TabFolderLayout()); top.setContent(tabFolder); ViewForm bottom= new ViewForm(sashForm, SWT.NONE); ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP); bottom.setTopCenter(failureToolBar); fFailureView= new FailureTraceView(bottom, this); bottom.setContent(fFailureView.getComposite()); CLabel label= new CLabel(bottom, SWT.NONE); label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$ label.setImage(fStackViewIcon); bottom.setTopLeft(label); // fill the failure trace viewer toolbar ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar); failureToolBarmanager.add(new EnableStackFilterAction(fFailureView)); failureToolBarmanager.update(true); sashForm.setWeights(new int[]{50, 50}); return sashForm; } private void reset(final int testCount) { postAsyncRunnable(new Runnable() { public void run() { if (isDisposed()) return; fCounterPanel.reset(); fFailureView.clear(); fProgressBar.reset(); clearStatus(); start(testCount); } }); fExecutedTests= 0; fFailures= 0; fErrors= 0; fTestCount= testCount; aboutToStart(); fTestInfos.clear(); fFirstFailure= null; } private void clearStatus() { getStatusLine().setMessage(null); getStatusLine().setErrorMessage(null); } public void setFocus() { if (fActiveRunView != null) fActiveRunView.setFocus(); } public void createPartControl(Composite parent) { GridLayout gridLayout= new GridLayout(); gridLayout.marginWidth= 0; parent.setLayout(gridLayout); IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager toolBar= actionBars.getToolBarManager(); toolBar.add(new StopAction()); toolBar.add(new RerunLastAction()); actionBars.updateActionBars(); Composite counterPanel= createProgressCountPanel(parent); counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); SashForm sashForm= createSashForm(parent); sashForm.setLayoutData(new GridData(GridData.FILL_BOTH)); actionBars.setGlobalActionHandler( IWorkbenchActionConstants.COPY, new CopyTraceAction(fFailureView)); JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); fOriginalViewImage= getTitleImage(); fProgressImages= new ProgressImages(); WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW); } private IStatusLineManager getStatusLine() { // we want to show messages globally hence we // have to go throgh the active part IViewSite site= getViewSite(); IWorkbenchPage page= site.getPage(); IWorkbenchPart activePart= page.getActivePart(); if (activePart instanceof IViewPart) { IViewPart activeViewPart= (IViewPart)activePart; IViewSite activeViewSite= activeViewPart.getViewSite(); return activeViewSite.getActionBars().getStatusLineManager(); } if (activePart instanceof IEditorPart) { IEditorPart activeEditorPart= (IEditorPart)activePart; IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); } // no active part return getViewSite().getActionBars().getStatusLineManager(); } private Composite createProgressCountPanel(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout()); fProgressBar = new JUnitProgressBar(composite); fProgressBar.setLayoutData( new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); fCounterPanel = new CounterPanel(composite); fCounterPanel.setLayoutData( new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); return composite; } public TestRunInfo getTestInfo(String testName) { if (testName == null) return null; return (TestRunInfo) fTestInfos.get(testName); } public void handleTestSelected(String testName) { TestRunInfo testInfo= getTestInfo(testName); if (testInfo == null) { showFailure(""); //$NON-NLS-1$ } else { showFailure(testInfo.fTrace); } } private void showFailure(final String failure) { postSyncRunnable(new Runnable() { public void run() { if (!isDisposed()) fFailureView.showFailure(failure); } }); } public IJavaProject getLaunchedProject() { return fTestProject; } protected static Image createImage(String path) { try { ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path)); return id.createImage(); } catch (MalformedURLException e) { // fall through } return null; } private boolean isDisposed() { return fIsDisposed || fCounterPanel.isDisposed(); } private Display getDisplay() { return getViewSite().getShell().getDisplay(); } /** * @see IWorkbenchPart#getTitleImage() */ public Image getTitleImage() { if (fOriginalViewImage == null) fOriginalViewImage= super.getTitleImage(); if (fViewImage == null) return super.getTitleImage(); return fViewImage; } public void propertyChange(PropertyChangeEvent event) { if (isDisposed()) return; if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) { if (!JUnitPreferencePage.getShowOnErrorOnly()) { fViewImage= fOriginalViewImage; firePropertyChange(IWorkbenchPart.PROP_TITLE); } } } void codeHasChanged() { postAsyncRunnable(new Runnable() { public void run() { if (isDisposed()) return; if (fDirtyListener != null) { JavaCore.removeElementChangedListener(fDirtyListener); fDirtyListener= null; } if (fViewImage == fTestRunOKIcon) fViewImage= fTestRunOKDirtyIcon; else if (fViewImage == fTestRunFailIcon) fViewImage= fTestRunFailDirtyIcon; firePropertyChange(IWorkbenchPart.PROP_TITLE); } }); } boolean isCreated() { return fCounterPanel != null; } }
19,855
Bug 19855 Test class not found in project [JUnit]
Is this a bug or am I missing something? I have a class which the JUnit Failure Trace window seems unable to GoTo, instead bringing up an error dialog which reads, "Test class not found in project". Steps: [1] Run a JUnit launch configuration which has failures. [2] In the failures tab, select "test_mumble". Right-menu/GoTo has the expected, correct behavior. [3] In the Failure Trace window below, I see the stack trace. I can double click or right-menu/GoTo all but one of the line in this window that correspond to my code, and be taken to the appropriate code position. For this trace, however, I cannot double click or use right-menu/GoTo for the method which raised an assert exception. If I try, I get the "Test class not found in project" error. I should point out that the assert is not being raised in test code, but in an unimplemented stub. Possibly relevant: The actual assert is in a method of a static inner class, said method looking roughly like double[] apply(double[] vectorIn, Space space) { assert false : "nyi"; return null; }
resolved fixed
6c49c68
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T16:37:29Z
2002-06-10T23:00:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureTraceView.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.ui; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; /** * A view that shows a stack trace of a failed test. */ class FailureTraceView implements IMenuListener { private static final String FRAME_PREFIX= "at "; //$NON-NLS-1$ private Table fTable; private TestRunnerViewPart fTestRunner; private String fInputTrace; private final Image fStackIcon= TestRunnerViewPart.createImage("obj16/stkfrm_obj.gif"); //$NON-NLS-1$ private final Image fExceptionIcon= TestRunnerViewPart.createImage("obj16/exc_catch.gif"); //$NON-NLS-1$ public FailureTraceView(Composite parent, TestRunnerViewPart testRunner) { fTable= new Table(parent, SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL); fTestRunner= testRunner; fTable.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent e){ handleDoubleClick(e); } }); initMenu(); parent.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { disposeIcons(); } }); } void handleDoubleClick(MouseEvent e) { if(fTable.getSelection().length != 0) { Action a= createOpenEditorAction(getSelectedText()); if (a != null) a.run(); } } private void initMenu() { MenuManager menuMgr= new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); Menu menu= menuMgr.createContextMenu(fTable); fTable.setMenu(menu); } public void menuAboutToShow(IMenuManager manager) { if (fTable.getSelectionCount() > 0) { Action a= createOpenEditorAction(getSelectedText()); if (a != null) manager.add(a); } manager.add(new CopyTraceAction(FailureTraceView.this)); } public String getTrace() { return fInputTrace; } private String getSelectedText() { return fTable.getSelection()[0].getText(); } private Action createOpenEditorAction(String traceLine) { try { //TODO: works for JDK stack trace only String testName= traceLine; testName= testName.substring(testName.indexOf(FRAME_PREFIX)); //$NON-NLS-1$ testName= testName.substring(FRAME_PREFIX.length(), testName.indexOf('(')).trim(); testName= testName.substring(0, testName.lastIndexOf('.')); String lineNumber= traceLine; lineNumber= lineNumber.substring(lineNumber.indexOf(':') + 1, lineNumber.indexOf(")")); //$NON-NLS-1$ int line= Integer.valueOf(lineNumber).intValue(); return new OpenEditorAtLineAction(fTestRunner, testName, line); } catch(NumberFormatException e) { } catch(IndexOutOfBoundsException e) { } return null; } void disposeIcons(){ if (fExceptionIcon != null && !fExceptionIcon.isDisposed()) fExceptionIcon.dispose(); if (fStackIcon != null && !fStackIcon.isDisposed()) fStackIcon.dispose(); } /** * Returns the composite used to present the trace */ public Composite getComposite(){ return fTable; } /** * Refresh the table from the the trace. */ public void refresh() { updateTable(fInputTrace); } /** * Shows a TestFailure */ public void showFailure(String trace) { if (fInputTrace == trace) return; fInputTrace= trace; updateTable(trace); } private void updateTable(String trace) { if(trace == null || trace.trim().equals("")) { //$NON-NLS-1$ clear(); return; } trace= trace.trim(); fTable.setRedraw(false); fTable.removeAll(); fillTable(filterStack(trace)); fTable.setRedraw(true); } protected void fillTable(String trace) { StringReader stringReader= new StringReader(trace); BufferedReader bufferedReader= new BufferedReader(stringReader); String line; try { // first line contains the thrown exception line= bufferedReader.readLine(); if (line == null) return; TableItem tableItem= new TableItem(fTable, SWT.NONE); String itemLabel= line.replace('\t', ' '); tableItem.setText(itemLabel); tableItem.setImage(fExceptionIcon); // the stack frames of the trace while ((line= bufferedReader.readLine()) != null) { itemLabel= line.replace('\t', ' '); tableItem= new TableItem(fTable, SWT.NONE); // heuristic for detecting a stack frame - works for JDK if ((itemLabel.indexOf(" at ") >= 0)) { //$NON-NLS-1$ tableItem.setImage(fStackIcon); } tableItem.setText(itemLabel); } } catch (IOException e) { TableItem tableItem= new TableItem(fTable, SWT.NONE); tableItem.setText(trace); } } /** * Shows other information than a stack trace. */ public void setInformation(String text) { clear(); TableItem tableItem= new TableItem(fTable, SWT.NONE); tableItem.setText(text); } /** * Clears the non-stack trace info */ public void clear() { fTable.removeAll(); fInputTrace= null; } private String filterStack(String stackTrace) { if (!JUnitPreferencePage.getFilterStack() || stackTrace == null) return stackTrace; StringWriter stringWriter= new StringWriter(); PrintWriter printWriter= new PrintWriter(stringWriter); StringReader stringReader= new StringReader(stackTrace); BufferedReader bufferedReader= new BufferedReader(stringReader); String line; String[] patterns= JUnitPreferencePage.getFilterPatterns(); try { while ((line= bufferedReader.readLine()) != null) { if (!filterLine(patterns, line)) printWriter.println(line); } } catch (IOException e) { return stackTrace; // return the stack unfiltered } return stringWriter.toString(); } private boolean filterLine(String[] patterns, String line) { String pattern; int len; for (int i= (patterns.length - 1); i >= 0; --i) { pattern= patterns[i]; len= pattern.length() - 1; if (pattern.charAt(len) == '*') { //strip trailing * from a package filter pattern= pattern.substring(0, len); } else if (Character.isUpperCase(pattern.charAt(0))) { //class in the default package pattern= FRAME_PREFIX + pattern + '.'; } else { //class names start w/ an uppercase letter after the . final int lastDotIndex= pattern.lastIndexOf('.'); if ((lastDotIndex != -1) && (lastDotIndex != len) && Character.isUpperCase(pattern.charAt(lastDotIndex + 1))) pattern += '.'; //append . to a class filter } if (line.indexOf(pattern) > 0) return true; } return false; } }
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_in/TestNested.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_out/TestNested.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui.tests.refactoring/test
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/TryCatchBlock.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
extension/org/eclipse/jdt/internal/corext/dom/CodeScopeBuilder.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallContext.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CodeScopeBuilder.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceProvider.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchAnalyzer.java
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,379
Bug 31379 Surround with try/catch should use unique identifier for exception
Build id: 200302061700 Surround with try/catch should avoid collision with existing identifiers when declaring the catch-block variable. For the following code snippet: try { throw new Exception(); } catch (Exception e) { throw new Exception(); // <<== problem marker } When accepting the quick-fix suggested for the problematic line, the following code results: try { throw new Exception(); } catch (Exception e) { try { throw new Exception(); } catch (Exception e) { // <<== problem marker // TODO Auto-generated catch block e.printStackTrace(); } } Now there is a compiler error in the inner catch: "Duplicate argument e".
resolved fixed
82df8bb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:19:33Z
2003-02-07T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java
27,889
Bug 27889 [JUnit] Launcher; all tests in default package ... empty TF
If you select "All tests in Project, Source Folder or Package" and select the default package the TF will be empty. There is no visual indication that one has selected the default package. It should be similar to the indicator in Package Explorer/View: (default package)
closed fixed
42da73f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:52:49Z
2002-12-07T16:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitMainTab.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * Sebastian Davids: [email protected] ******************************************************************************/ package org.eclipse.jdt.internal.junit.launcher; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.junit.ui.JUnitMessages; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.SelectionDialog; /** * This tab appears in the LaunchConfigurationDialog for launch configurations that * require Java-specific launching information such as a main type and JRE. */ public class JUnitMainTab extends JUnitLaunchConfigurationTab { // Project UI widgets private Label fProjLabel; private Text fProjText; private Button fProjButton; private Button fKeepRunning; // Test class UI widgets private Text fTestText; private Button fSearchButton; private final Image fTestIcon= createImage("obj16/test.gif"); //$NON-NLS-1$ private Label fTestMethodLabel; private Text fContainerText; private IJavaElement fContainerElement; private Button fContainerSearchButton; private Button fTestContainerRadioButton; private Button fTestRadioButton; /** * @see ILaunchConfigurationTab#createControl(TabItem) */ public void createControl(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); setControl(comp); GridLayout topLayout = new GridLayout(); topLayout.numColumns= 2; comp.setLayout(topLayout); new Label(comp, SWT.NONE); createProjectGroup(comp); createTestSelectionGroup(comp); createTestContainerSelectionGroup(comp); createKeepAliveGroup(comp); } private void createTestContainerSelectionGroup(Composite comp) { GridData gd; fTestContainerRadioButton= new Button(comp, SWT.RADIO); fTestContainerRadioButton.setText(JUnitMessages.getString("JUnitMainTab.label.container")); //$NON-NLS-1$ gd = new GridData(); gd.horizontalSpan = 2; fTestContainerRadioButton.setLayoutData(gd); fTestContainerRadioButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (fTestContainerRadioButton.getSelection()) testModeChanged(); } public void widgetDefaultSelected(SelectionEvent e) { } }); fContainerText = new Text(comp, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= 20; fContainerText.setLayoutData(gd); fContainerText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); } }); fContainerSearchButton = new Button(comp, SWT.PUSH); fContainerSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$ fContainerSearchButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { handleContainerSearchButtonSelected(); } }); setButtonGridData(fContainerSearchButton); } private void handleContainerSearchButtonSelected() { IJavaElement javaElement= chooseContainer(fContainerElement); if (javaElement != null) { fContainerElement= javaElement; fContainerText.setText(javaElement.getElementName()); } } public void createKeepAliveGroup(Composite comp) { GridData gd; fKeepRunning = new Button(comp, SWT.CHECK); fKeepRunning.setText(JUnitMessages.getString("JUnitMainTab.label.keeprunning")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.horizontalSpan= 2; fKeepRunning.setLayoutData(gd); } public void createTestSelectionGroup(Composite comp) { GridData gd; fTestRadioButton= new Button(comp, SWT.RADIO /*| SWT.LEFT*/); fTestRadioButton.setText(JUnitMessages.getString("JUnitMainTab.label.test")); //$NON-NLS-1$ gd = new GridData(); gd.horizontalSpan = 2; fTestRadioButton.setLayoutData(gd); fTestRadioButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (fTestRadioButton.getSelection()) testModeChanged(); } public void widgetDefaultSelected(SelectionEvent e) { } }); fTestText = new Text(comp, SWT.SINGLE | SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= 20; fTestText.setLayoutData(gd); fTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); } }); fSearchButton = new Button(comp, SWT.PUSH); fSearchButton.setEnabled(fProjText.getText().length() > 0); fSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$ fSearchButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { handleSearchButtonSelected(); } }); setButtonGridData(fSearchButton); fTestMethodLabel= new Label(comp, SWT.NONE); fTestMethodLabel.setText(""); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan = 2; gd.horizontalIndent= 20; fTestMethodLabel.setLayoutData(gd); } public void createProjectGroup(Composite comp) { GridData gd; fProjLabel = new Label(comp, SWT.NONE); fProjLabel.setText(JUnitMessages.getString("JUnitMainTab.label.project")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan = 2; fProjLabel.setLayoutData(gd); fProjText= new Text(comp, SWT.SINGLE | SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); fProjText.setLayoutData(gd); fProjText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); boolean isSingleTestMode= fTestRadioButton.getSelection(); fSearchButton.setEnabled(isSingleTestMode && fProjText.getText().length() > 0); } }); fProjButton = new Button(comp, SWT.PUSH); fProjButton.setText(JUnitMessages.getString("JUnitMainTab.label.browse")); //$NON-NLS-1$ fProjButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { handleProjectButtonSelected(); } }); setButtonGridData(fProjButton); } protected static Image createImage(String path) { try { ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path)); return id.createImage(); } catch (MalformedURLException e) { // fall through } return null; } /** * @see ILaunchConfigurationTab#initializeFrom(ILaunchConfiguration) */ public void initializeFrom(ILaunchConfiguration config) { updateProjectFromConfig(config); String containerHandle= ""; //$NON-NLS-1$ try { containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ } catch (CoreException ce) { } if (containerHandle.length() > 0) updateTestContainerFromConfig(config); else updateTestTypeFromConfig(config); updateKeepRunning(config); } private void updateKeepRunning(ILaunchConfiguration config) { boolean running= false; try { running= config.getAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, false); } catch (CoreException ce) { } fKeepRunning.setSelection(running); } protected void updateProjectFromConfig(ILaunchConfiguration config) { String projectName= ""; //$NON-NLS-1$ try { projectName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ } catch (CoreException ce) { } fProjText.setText(projectName); } protected void updateTestTypeFromConfig(ILaunchConfiguration config) { String testTypeName= ""; //$NON-NLS-1$ String testMethodName= ""; //$NON-NLS-1$ try { testTypeName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$ testMethodName = config.getAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, ""); //$NON-NLS-1$ } catch (CoreException ce) { } fTestRadioButton.setSelection(true); setEnableSingleTestGroup(true); setEnableContainerTestGroup(false); fTestContainerRadioButton.setSelection(false); fTestText.setText(testTypeName); fContainerText.setText(""); //$NON-NLS-1$ if (!"".equals(testMethodName)) { //$NON-NLS-1$ fTestMethodLabel.setText(JUnitMessages.getString("JUnitMainTab.label.method")+testMethodName); //$NON-NLS-1$ } else { fTestMethodLabel.setText(""); //$NON-NLS-1$ } } protected void updateTestContainerFromConfig(ILaunchConfiguration config) { String containerHandle= ""; //$NON-NLS-1$ try { containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ if (containerHandle.length() > 0) { fContainerElement= JavaCore.create(containerHandle); } } catch (CoreException ce) { } fTestContainerRadioButton.setSelection(true); setEnableSingleTestGroup(false); setEnableContainerTestGroup(true); fTestRadioButton.setSelection(false); if (fContainerElement != null) fContainerText.setText(fContainerElement.getElementName()); fTestText.setText(""); //$NON-NLS-1$ } /** * @see ILaunchConfigurationTab#performApply(ILaunchConfigurationWorkingCopy) */ public void performApply(ILaunchConfigurationWorkingCopy config) { config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)fProjText.getText()); if (fTestContainerRadioButton.getSelection() && fContainerElement != null) { config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, fContainerElement.getHandleIdentifier()); //bug 26293 config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$ } else { config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)fTestText.getText()); //bug 26293 config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ } config.setAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, fKeepRunning.getSelection()); } /** * @see ILaunchConfigurationTab#dispose() */ public void dispose() { super.dispose(); fTestIcon.dispose(); } /** * @see AbstractLaunchConfigurationTab#getImage() */ public Image getImage() { return fTestIcon; } /** * Show a dialog that lists all main types */ protected void handleSearchButtonSelected() { Shell shell = getShell(); IJavaProject javaProject = getJavaProject(); SelectionDialog dialog = new TestSelectionDialog(shell, new ProgressMonitorDialog(shell), javaProject); dialog.setTitle(JUnitMessages.getString("JUnitMainTab.testdialog.title")); //$NON-NLS-1$ dialog.setMessage(JUnitMessages.getString("JUnitMainTab.testdialog.message")); //$NON-NLS-1$ if (dialog.open() == SelectionDialog.CANCEL) { return; } Object[] results = dialog.getResult(); if ((results == null) || (results.length < 1)) { return; } IType type = (IType)results[0]; if (type != null) { fTestText.setText(type.getFullyQualifiedName()); javaProject = type.getJavaProject(); fProjText.setText(javaProject.getElementName()); } } /** * Show a dialog that lets the user select a project. This in turn provides * context for the main type, allowing the user to key a main type name, or * constraining the search for main types to the specified project. */ protected void handleProjectButtonSelected() { IJavaProject project = chooseJavaProject(); if (project == null) { return; } String projectName = project.getElementName(); fProjText.setText(projectName); } /** * Realize a Java Project selection dialog and return the first selected project, * or null if there was none. */ protected IJavaProject chooseJavaProject() { IJavaProject[] projects; try { projects= JavaCore.create(getWorkspaceRoot()).getJavaProjects(); } catch (JavaModelException e) { JUnitPlugin.log(e.getStatus()); projects= new IJavaProject[0]; } ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider); dialog.setTitle(JUnitMessages.getString("JUnitMainTab.projectdialog.title")); //$NON-NLS-1$ dialog.setMessage(JUnitMessages.getString("JUnitMainTab.projectdialog.message")); //$NON-NLS-1$ dialog.setElements(projects); IJavaProject javaProject = getJavaProject(); if (javaProject != null) { dialog.setInitialSelections(new Object[] { javaProject }); } if (dialog.open() == ElementListSelectionDialog.OK) { return (IJavaProject) dialog.getFirstResult(); } return null; } /** * Return the IJavaProject corresponding to the project name in the project name * text field, or null if the text does not match a project name. */ protected IJavaProject getJavaProject() { String projectName = fProjText.getText().trim(); if (projectName.length() < 1) { return null; } return getJavaModel().getJavaProject(projectName); } /** * Convenience method to get the workspace root. */ private IWorkspaceRoot getWorkspaceRoot() { return ResourcesPlugin.getWorkspace().getRoot(); } /** * Convenience method to get access to the java model. */ private IJavaModel getJavaModel() { return JavaCore.create(getWorkspaceRoot()); } /** * @see ILaunchConfigurationTab#isValid(ILaunchConfiguration) */ public boolean isValid(ILaunchConfiguration config) { setErrorMessage(null); setMessage(null); String projectName = fProjText.getText().trim(); if (projectName.length() > 0) { if (!ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).exists()) { setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.projectnotexists")); //$NON-NLS-1$ return false; } } String testName = fTestText.getText().trim(); if (testName.length() == 0 && fContainerElement == null) { setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.testnotdefined")); //$NON-NLS-1$ return false; } // TO DO should verify that test exists return true; } private void testModeChanged() { boolean isSingleTestMode= fTestRadioButton.getSelection(); setEnableSingleTestGroup(isSingleTestMode); setEnableContainerTestGroup(!isSingleTestMode); } private void setEnableContainerTestGroup(boolean enabled) { fContainerSearchButton.setEnabled(enabled); fContainerText.setEnabled(enabled); } private void setEnableSingleTestGroup(boolean enabled) { fSearchButton.setEnabled(enabled && fProjText.getText().length() > 0); fTestText.setEnabled(enabled); fTestMethodLabel.setEnabled(enabled); } /** * @see ILaunchConfigurationTab#setDefaults(ILaunchConfigurationWorkingCopy) */ public void setDefaults(ILaunchConfigurationWorkingCopy config) { IJavaElement javaElement = getContext(); if (javaElement != null) { initializeJavaProject(javaElement, config); } else { // We set empty attributes for project & main type so that when one config is // compared to another, the existence of empty attributes doesn't cause an // incorrect result (the performApply() method can result in empty values // for these attributes being set on a config if there is nothing in the // corresponding text boxes) config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ } initializeTestAttributes(javaElement, config); } private void initializeTestAttributes(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) { if (javaElement != null && javaElement.getElementType() < IJavaElement.COMPILATION_UNIT) initializeTestContainer(javaElement, config); else initializeTestType(javaElement, config); } private void initializeTestContainer(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) { config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, javaElement.getHandleIdentifier()); initializeName(config, javaElement.getElementName()); } private void initializeName(ILaunchConfigurationWorkingCopy config, String name) { if (name == null) { name= ""; //$NON-NLS-1$ } if (name.length() > 0) { int index = name.lastIndexOf('.'); if (index > 0) { name = name.substring(index + 1); } name= getLaunchConfigurationDialog().generateName(name); config.rename(name); } } /** * Set the main type & name attributes on the working copy based on the IJavaElement */ protected void initializeTestType(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) { String name= ""; //$NON-NLS-1$ try { // we only do a search for compilation units or class files or // or source references if ((javaElement instanceof ICompilationUnit) || (javaElement instanceof ISourceReference) || (javaElement instanceof IClassFile)) { IType[] types = TestSearchEngine.findTests(new BusyIndicatorRunnableContext(), new Object[] {javaElement}); if ((types == null) || (types.length < 1)) { return; } // Simply grab the first main type found in the searched element name = types[0].getFullyQualifiedName(); } } catch (InterruptedException ie) { } catch (InvocationTargetException ite) { } if (name == null) name= ""; //$NON-NLS-1$ config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, name); initializeName(config, name); } /** * @see ILaunchConfigurationTab#getName() */ public String getName() { return JUnitMessages.getString("JUnitMainTab.tab.label"); //$NON-NLS-1$ } private IJavaElement chooseContainer(IJavaElement initElement) { Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) { public boolean isSelectedValid(Object element) { return true; } }; acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { public boolean select(Viewer viewer, Object parent, Object element) { return super.select(viewer, parent, element); } }; StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider(); ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider); dialog.setValidator(validator); dialog.setSorter(new JavaElementSorter()); dialog.setTitle(JUnitMessages.getString("JUnitMainTab.folderdialog.title")); //$NON-NLS-1$ dialog.setMessage(JUnitMessages.getString("JUnitMainTab.folderdialog.message")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(JavaCore.create(getWorkspaceRoot())); dialog.setInitialSelection(initElement); dialog.setAllowMultiple(false); if (dialog.open() == ElementTreeSelectionDialog.OK) { Object element= dialog.getFirstResult(); return (IJavaElement)element; } return null; } }
19,974
Bug 19974 Packages view: back / forward buttons do not show frame name [package explorer]
Build 20020611 In packages view, - select a container - Navigate / Go Into - hover over Back button - it says simply "Back" It should say "Back to Workspace". Compare with Navigator.
resolved fixed
82656d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:57:21Z
2002-06-12T02:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ITreeViewerListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeExpansionEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.core.runtime.IPath; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTarget; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ISetSelectionTarget; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.ui.IPackagesViewPart; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; /** * The ViewPart for the ProjectExplorer. It listens to part activation events. * When selection linking with the editor is enabled the view selection tracks * the active editor page. Similarly when a resource is selected in the packages * view the corresponding editor is activated. */ public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IShowInTarget, IPackagesViewPart, IPropertyChangeListener, IViewPartInputProvider { private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical private static final int HIERARCHICAL_LAYOUT= 0x1; private static final int FLAT_LAYOUT= 0x2; public final static String VIEW_ID= JavaUI.ID_PACKAGES; // Persistance tags. static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$ static final String TAG_ELEMENT= "element"; //$NON-NLS-1$ static final String TAG_PATH= "path"; //$NON-NLS-1$ static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$ static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$ static final String TAG_FILTERS = "filters"; //$NON-NLS-1$ static final String TAG_FILTER = "filter"; //$NON-NLS-1$ static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$ private PackageExplorerContentProvider fContentProvider; private PackageExplorerActionGroup fActionSet; private ProblemTreeViewer fViewer; private Menu fContextMenu; private IMemento fMemento; private ISelectionChangedListener fSelectionListener; private String fWorkingSetName; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; private ITreeViewerListener fExpansionListener= new ITreeViewerListener() { public void treeCollapsed(TreeExpansionEvent event) { } public void treeExpanded(TreeExpansionEvent event) { Object element= event.getElement(); if (element instanceof ICompilationUnit || element instanceof IClassFile) expandMainType(element); } }; private PackageExplorerLabelProvider fLabelProvider; /* (non-Javadoc) * Method declared on IViewPart. */ private boolean fLinkingEnabled; public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; restoreLayoutState(memento); } private void restoreLayoutState(IMemento memento) { Integer state= null; if (memento != null) state= memento.getInteger(TAG_LAYOUT); // If no memento try an restore from preference store if(state == null) { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); state= new Integer(store.getInt(TAG_LAYOUT)); } if (state.intValue() == FLAT_LAYOUT) fIsCurrentLayoutFlat= true; else if (state.intValue() == HIERARCHICAL_LAYOUT) fIsCurrentLayoutFlat= false; else fIsCurrentLayoutFlat= true; } /** * Returns the package explorer part of the active perspective. If * there isn't any package explorer part <code>null</code> is returned. */ public static PackageExplorerPart getFromActivePerspective() { IWorkbenchPage activePage= JavaPlugin.getActivePage(); if (activePage == null) return null; IViewPart view= activePage.findView(VIEW_ID); if (view instanceof PackageExplorerPart) return (PackageExplorerPart)view; return null; } /** * Makes the package explorer part visible in the active perspective. If there * isn't a package explorer part registered <code>null</code> is returned. * Otherwise the opened view part is returned. */ public static PackageExplorerPart openInActivePerspective() { try { return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID); } catch(PartInitException pe) { return null; } } public void dispose() { if (fContextMenu != null && !fContextMenu.isDisposed()) fContextMenu.dispose(); getSite().getPage().removePartListener(fPartListener); JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); if (fViewer != null) fViewer.removeTreeListener(fExpansionListener); if (fActionSet != null) fActionSet.dispose(); super.dispose(); } /** * Implementation of IWorkbenchPart.createPartControl(Composite) */ public void createPartControl(Composite parent) { fViewer= createViewer(parent); fViewer.setUseHashlookup(true); fViewer.setComparer(new PackageExplorerElementComparer()); setProviders(); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getTree()); fViewer.getTree().setMenu(fContextMenu); // Register viewer with site. This must be done before making the actions. IWorkbenchPartSite site= getSite(); site.registerContextMenu(menuMgr, fViewer); site.setSelectionProvider(fViewer); site.getPage().addPartListener(fPartListener); if (fMemento != null) { restoreLinkingEnabled(fMemento); } makeActions(); // call before registering for selection changes // Set input after filter and sorter has been set. This avoids resorting and refiltering. restoreFilterAndSorter(); fViewer.setInput(findInputElement()); initDragAndDrop(); initKeyListener(); fSelectionListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { handleSelectionChanged(event); } }; fViewer.addSelectionChangedListener(fSelectionListener); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { fActionSet.handleDoubleClick(event); } }); fViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { fActionSet.handleOpen(event); } }); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); fViewer.addTreeListener(fExpansionListener); if (fMemento != null) restoreUIState(fMemento); fMemento= null; // Set help for the view JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW); fillActionBars(); updateTitle(); } /** * This viewer ensures that non-leaves in the hierarchical * layout are not removed by any filters. * * @since 2.1 */ private ProblemTreeViewer createViewer(Composite parent) { return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) { /* * @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object) */ protected Object[] getFilteredChildren(Object parent) { List list = new ArrayList(); ViewerFilter[] filters = fViewer.getFilters(); Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent); for (int i = 0; i < children.length; i++) { Object object = children[i]; if (!isEssential(object)) { object = filter(object, parent, filters); if (object != null) { list.add(object); } } else list.add(object); } return list.toArray(); } // Sends the object through the given filters private Object filter(Object object, Object parent, ViewerFilter[] filters) { for (int i = 0; i < filters.length; i++) { ViewerFilter filter = filters[i]; if (!filter.select(fViewer, parent, object)) return null; } return object; } /* Checks if a filtered object in essential (ie. is a parent that * should not be removed). */ private boolean isEssential(Object object) { try { if (!isFlatLayout() && object instanceof IPackageFragment) { IPackageFragment fragment = (IPackageFragment) object; return !fragment.isDefaultPackage() && fragment.hasSubpackages(); } } catch (JavaModelException e) { JavaPlugin.log(e); } return false; } }; } /** * Answers whether this part shows the packages flat or hierarchical. * * @since 2.1 */ boolean isFlatLayout() { return fIsCurrentLayoutFlat; } private void setProviders() { //content provider must be set before the label provider fContentProvider= createContentProvider(); fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setContentProvider(fContentProvider); fLabelProvider= createLabelProvider(); fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false)); // problem decoration provided by PackageLabelProvider } void toggleLayout() { // Update current state and inform content and label providers fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat; saveLayoutState(null); fContentProvider.setIsFlatLayout(isFlatLayout()); fLabelProvider.setIsFlatLayout(isFlatLayout()); fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } /** * This method should only be called inside this class * and from test cases. */ public PackageExplorerContentProvider createContentProvider() { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS)); return new PackageExplorerContentProvider(showCUChildren, reconcile); } private PackageExplorerLabelProvider createLabelProvider() { return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, fContentProvider); } private void fillActionBars() { IActionBars actionBars= getViewSite().getActionBars(); fActionSet.fillActionBars(actionBars); } private Object findInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IWorkspace) { return JavaCore.create(((IWorkspace)input).getRoot()); } else if (input instanceof IContainer) { IJavaElement element= JavaCore.create((IContainer)input); if (element != null && element.exists()) return element; return input; } //1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective // we can't handle the input // fall back to show the workspace return JavaCore.create(JavaPlugin.getWorkspace().getRoot()); } /** * Answer the property defined by key. */ public Object getAdapter(Class key) { if (key.equals(ISelectionProvider.class)) return fViewer; if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(key); } /** * Returns the tool tip text for the given element. */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$ } else { result= path.makeRelative().toString(); } } if (fWorkingSetName == null) return result; String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$ if (result.length() == 0) return wsstr; return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$ } public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } /** * @see IWorkbenchPart#setFocus() */ public void setFocus() { fViewer.getTree().setFocus(); } /** * Returns the current selection. */ private ISelection getSelection() { return fViewer.getSelection(); } //---- Action handling ---------------------------------------------------------- /** * Called when the context menu is about to open. Override * to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); fActionSet.setContext(new ActionContext(getSelection())); fActionSet.fillContextMenu(menu); fActionSet.setContext(null); } private void makeActions() { fActionSet= new PackageExplorerActionGroup(this); } //---- Event handling ---------------------------------------------------------- private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance(), FileTransfer.getInstance()}; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fViewer), new FileTransferDropAdapter(fViewer) }; fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); // Drag Adapter Control control= fViewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fViewer), new ResourceTransferDragAdapter(fViewer), new FileTransferDragAdapter(fViewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners) { public void dragStart(DragSourceEvent event) { IStructuredSelection selection= (IStructuredSelection)getSelection(); if (selection.isEmpty()) { event.doit= false; return; } for (Iterator iter= selection.iterator(); iter.hasNext(); ) { if (iter.next() instanceof IMember) { setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)}); break; } } super.dragStart(event); } }); } /** * Handles selection changed in viewer. * Updates global actions. * Links to editor (if option enabled) */ private void handleSelectionChanged(SelectionChangedEvent event) { IStructuredSelection selection= (IStructuredSelection) event.getSelection(); fActionSet.handleSelectionChanged(event); // if (OpenStrategy.getOpenMethod() != OpenStrategy.SINGLE_CLICK) linkToEditor(selection); } public void selectReveal(ISelection selection) { selectReveal(selection, 0); } private void selectReveal(final ISelection selection, final int count) { Control ctrl= getViewer().getControl(); if (ctrl == null || ctrl.isDisposed()) return; ISelection javaSelection= convertSelection(selection); fViewer.setSelection(javaSelection, true); PackageExplorerContentProvider provider= (PackageExplorerContentProvider)getViewer().getContentProvider(); ISelection cs= fViewer.getSelection(); // If we have Pending changes and the element could not be selected then // we try it again on more time by posting the select and reveal asynchronuoulsy // to the event queue. See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=30700 // for a discussion of the underlying problem. if (count == 0 && provider.hasPendingChanges() && !javaSelection.equals(cs)) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { selectReveal(selection, count + 1); } }); } } private ISelection convertSelection(ISelection s) { if (!(s instanceof IStructuredSelection)) return s; Object[] elements= ((StructuredSelection)s).toArray(); if (!containsResources(elements)) return s; for (int i= 0; i < elements.length; i++) { Object o= elements[i]; if (o instanceof IResource) { IJavaElement jElement= JavaCore.create((IResource)o); if (jElement != null && jElement.exists()) elements[i]= jElement; } } return new StructuredSelection(elements); } private boolean containsResources(Object[] elements) { for (int i = 0; i < elements.length; i++) { if (elements[i] instanceof IResource) return true; } return false; } public void selectAndReveal(Object element) { selectReveal(new StructuredSelection(element)); } boolean isLinkingEnabled() { return fLinkingEnabled; } /** * Initializes the linking enabled setting from the preference store. */ private void initLinkingEnabled() { fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { // ignore selection changes if the package explorer is not the active part. // In this case the selection change isn't triggered by a user. if (!isActivePart()) return; Object obj= selection.getFirstElement(); if (selection.size() == 1) { IEditorPart part= EditorUtility.isOpenInEditor(obj); if (part != null) { IWorkbenchPage page= getSite().getPage(); page.bringToTop(part); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) obj); } } } private boolean isActivePart() { return this == getSite().getPage().getActivePart(); } public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } saveExpansionState(memento); saveSelectionState(memento); saveLayoutState(memento); saveLinkingEnabled(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //saveScrollState(memento, fViewer.getTree()); fActionSet.saveFilterAndSorterState(memento); } private void saveLinkingEnabled(IMemento memento) { memento.putInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, fLinkingEnabled ? 1 : 0); } /** * Saves the current layout state. * * @param memento the memento to save the state into or * <code>null</code> to store the state in the preferences * @since 2.1 */ private void saveLayoutState(IMemento memento) { if (memento != null) { memento.putInteger(TAG_LAYOUT, getLayoutAsInt()); } else { //if memento is null save in preference store IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(TAG_LAYOUT, getLayoutAsInt()); } } private int getLayoutAsInt() { if (fIsCurrentLayoutFlat) return FLAT_LAYOUT; else return HIERARCHICAL_LAYOUT; } protected void saveScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position)); //save horizontal position bar= tree.getHorizontalBar(); position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position)); } protected void saveSelectionState(IMemento memento) { Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray(); if (elements.length > 0) { IMemento selectionMem= memento.createChild(TAG_SELECTION); for (int i= 0; i < elements.length; i++) { IMemento elementMem= selectionMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= elements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier()); } } } protected void saveExpansionState(IMemento memento) { Object expandedElements[]= fViewer.getVisibleExpandedElements(); if (expandedElements.length > 0) { IMemento expandedMem= memento.createChild(TAG_EXPANDED); for (int i= 0; i < expandedElements.length; i++) { IMemento elementMem= expandedMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= expandedElements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier()); } } } private void restoreFilterAndSorter() { fViewer.setSorter(new JavaElementSorter()); if (fMemento != null) fActionSet.restoreFilterAndSorterState(fMemento); } private void restoreUIState(IMemento memento) { restoreExpansionState(memento); restoreSelectionState(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //restoreScrollState(memento, fViewer.getTree()); } private void restoreLinkingEnabled(IMemento memento) { Integer val= memento.getInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); if (val != null) { fLinkingEnabled= val.intValue() != 0; } } protected void restoreScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_VERTICAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore, don't set scrollposition } } bar= tree.getHorizontalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_HORIZONTAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore don't set scroll position } } } protected void restoreSelectionState(IMemento memento) { IMemento childMem; childMem= memento.getChild(TAG_SELECTION); if (childMem != null) { ArrayList list= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) list.add(element); } fViewer.setSelection(new StructuredSelection(list)); } } protected void restoreExpansionState(IMemento memento) { IMemento childMem= memento.getChild(TAG_EXPANDED); if (childMem != null) { ArrayList elements= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) elements.add(element); } fViewer.setExpandedElements(elements.toArray()); } } /** * Create the KeyListener for doing the refresh on the viewer. */ private void initKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { fActionSet.handleKeyEvent(event); } }); } /** * An editor has been activated. Set the selection in this Packages Viewer * to be the editor's input, if linking is enabled. */ void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) return; showInput(getElementOfInput(editor.getEditorInput())); } boolean showInput(Object input) { Object element= null; if (input instanceof IFile && isOnClassPath((IFile)input)) { element= JavaCore.create((IFile)input); } if (element == null) // try a non Java resource element= input; if (element != null) { ISelection newSelection= new StructuredSelection(element); if (!fViewer.getSelection().equals(newSelection)) { try { fViewer.removeSelectionChangedListener(fSelectionListener); fViewer.setSelection(newSelection); while (element != null && fViewer.getSelection().isEmpty()) { // Try to select parent in case element is filtered element= getParent(element); if (element != null) { newSelection= new StructuredSelection(element); fViewer.setSelection(newSelection); } } } finally { fViewer.addSelectionChangedListener(fSelectionListener); } return true; } } return false; } private boolean isOnClassPath(IFile file) { IJavaProject jproject= JavaCore.create(file.getProject()); try { return jproject.isOnClasspath(file); } catch (JavaModelException e) { // fall through } return false; } /** * Returns the element's parent. * * @return the parent or <code>null</code> if there's no parent */ private Object getParent(Object element) { if (element instanceof IJavaElement) return ((IJavaElement)element).getParent(); else if (element instanceof IResource) return ((IResource)element).getParent(); // else if (element instanceof IStorage) { // can't get parent - see bug 22376 // } return null; } /** * A compilation unit or class was expanded, expand * the main type. */ void expandMainType(Object element) { try { IType type= null; if (element instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit)element; IType[] types= cu.getTypes(); if (types.length > 0) type= types[0]; } else if (element instanceof IClassFile) { IClassFile cf= (IClassFile)element; type= cf.getType(); } if (type != null) { final IType type2= type; Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) fViewer.expandToLevel(type2, 1); } }); } } } catch(JavaModelException e) { // no reveal } } /** * Returns the element contained in the EditorInput */ Object getElementOfInput(IEditorInput input) { if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); else if (input instanceof IFileEditorInput) return ((IFileEditorInput)input).getFile(); else if (input instanceof JarEntryEditorInput) return ((JarEntryEditorInput)input).getStorage(); return null; } /** * Returns the Viewer. */ TreeViewer getViewer() { return fViewer; } /** * Returns the TreeViewer. */ public TreeViewer getTreeViewer() { return fViewer; } boolean isExpandable(Object element) { if (fViewer == null) return false; return fViewer.isExpandable(element); } void setWorkingSetName(String workingSetName) { fWorkingSetName= workingSetName; } /** * Updates the title text and title tool tip. * Called whenever the input of the viewer changes. */ void updateTitle() { Object input= fViewer.getInput(); String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ if (input == null || (input instanceof IJavaModel)) { setTitle(viewName); setTitleToolTip(""); //$NON-NLS-1$ } else { String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$ setTitle(title); setTitleToolTip(getToolTipText(input)); } } /** * Sets the decorator for the package explorer. * * @param decorator a label decorator or <code>null</code> for no decorations. * @deprecated To be removed */ public void setLabelDecorator(ILabelDecorator decorator) { } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fViewer == null) return; boolean refreshViewer= false; if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) { fActionSet.updateActionBars(getViewSite().getActionBars()); boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); ((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren); refreshViewer= true; } else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { refreshViewer= true; } if (refreshViewer) fViewer.refresh(); } /* (non-Javadoc) * @see IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { if (fViewer != null) { return fViewer.getInput(); } return null; } public void collapseAll() { fViewer.getControl().setRedraw(false); fViewer.collapseToLevel(getViewPartInput(), TreeViewer.ALL_LEVELS); fViewer.getControl().setRedraw(true); } public PackageExplorerPart() { initLinkingEnabled(); } public boolean show(ShowInContext context) { Object input= context.getInput(); if (input instanceof IEditorInput) return showInput(getElementOfInput((IEditorInput)context.getInput())); ISelection selection= context.getSelection(); if (selection != null) { selectReveal(selection); return true; } return false; } /** * Returns the <code>IShowInSource</code> for this view. */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( getViewer().getInput(), getViewer().getSelection()); } }; } /** * @see IResourceNavigator#setLinkingEnabled(boolean) * @since 2.1 */ public void setLinkingEnabled(boolean enabled) { fLinkingEnabled= enabled; PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, enabled); if (enabled) { IEditorPart editor = getSite().getPage().getActiveEditor(); if (editor != null) { editorActivated(editor); } } } }
19,974
Bug 19974 Packages view: back / forward buttons do not show frame name [package explorer]
Build 20020611 In packages view, - select a container - Navigate / Go Into - hover over Back button - it says simply "Back" It should say "Back to Workspace". Compare with Navigator.
resolved fixed
82656d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T18:57:21Z
2002-06-12T02:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackagesFrameSource.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.packageview; import org.eclipse.ui.views.framelist.TreeFrame; import org.eclipse.ui.views.framelist.TreeViewerFrameSource; class PackagesFrameSource extends TreeViewerFrameSource { private PackageExplorerPart fPackagesExplorer; PackagesFrameSource(PackageExplorerPart explorer) { super(explorer.getViewer()); fPackagesExplorer= explorer; } protected TreeFrame createFrame(Object input) { TreeFrame frame = super.createFrame(input); frame.setToolTipText(fPackagesExplorer.getToolTipText(input)); return frame; } /** * Also updates the title of the packages explorer */ protected void frameChanged(TreeFrame frame) { super.frameChanged(frame); fPackagesExplorer.updateTitle(); } }
29,696
Bug 29696 JavaMarkerAnnotation.initialize() can be called in non UI thread.
Build I20020315 Refactoring uses documents and annotation models to actual perform the textual changes. Since refactoring operations can be executed in a non UI thread (e.g. when executed as an operation) the JavaMarkerAnnotation.initialize() method may be called in a non UI thread resulting in an assertion failure due to image creation. Caused by: org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java:110) at org.eclipse.jface.resource.ImageRegistry.<init> (ImageRegistry.java:51) at org.eclipse.jdt.internal.ui.JavaPluginImages.getImageRegistry (JavaPluginImages.java:341) at org.eclipse.jdt.internal.ui.JavaPluginImages.get (JavaPluginImages.java:317) at org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation.initialize (JavaMarkerAnnotation.java:111) at org.eclipse.ui.texteditor.MarkerAnnotation.<init> (MarkerAnnotation.java:111) at org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation.<init> (JavaMarkerAnnotation.java:53) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$Compilati onUnitAnnotationModel.createMarkerAnnotation (CompilationUnitDocumentProvider.java:381) at org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel.addMarkerAnnotation (AbstractMarkerAnnotationModel.java:215) at org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel.catchupWithMarkers (AbstractMarkerAnnotationModel.java:394) at org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel.connected (AbstractMarkerAnnotationModel.java:228) at org.eclipse.jface.text.source.AnnotationModel.connect (AnnotationModel.java:139) at org.eclipse.jdt.internal.corext.textmanipulation.TextBufferFactory.acquire (TextBufferFactory.java:88) at org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer.acquire (TextBuffer.java:371) at org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure.aquireTextBuff er(ImportsStructure.java:538) at org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure.<init> (ImportsStructure.java:85) at org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit.<init> (ImportEdit.java:33) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.getImportE dit(MoveCuUpdateCreator.java:217) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.addImport (MoveCuUpdateCreator.java:208) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.addImports ToDestinationPackage(MoveCuUpdateCreator.java:199) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.createChan geManager(MoveCuUpdateCreator.java:89) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.createChangeMa nager(MoveRefactoring.java:475) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.checkInput (MoveRefactoring.java:158) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
resolved fixed
dca18b8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T19:04:18Z
2003-01-17T07:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaMarkerAnnotation.java
/********************************************************************** Copyright (c) 2000, 2003 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.util.Iterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.text.Assert; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.MarkerUtilities; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugModelPresentation; import org.eclipse.search.ui.SearchUI; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.core.Util; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor; public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnotation { private static final int NO_IMAGE= 0; private static final int ORIGINAL_MARKER_IMAGE= 1; private static final int QUICKFIX_IMAGE= 2; private static final int QUICKFIX_ERROR_IMAGE= 3; private static final int OVERLAY_IMAGE= 4; private static final int GRAY_IMAGE= 5; private static final int BREAKPOINT_IMAGE= 6; private static Image fgQuickFixImage; private static Image fgQuickFixErrorImage; private static ImageRegistry fgGrayMarkersImageRegistry; private IDebugModelPresentation fPresentation; private IJavaAnnotation fOverlay; private boolean fNotRelevant= false; private AnnotationType fType; private int fImageType; private boolean fQuickFixIconEnabled; public JavaMarkerAnnotation(IMarker marker) { super(marker); } /* * @see MarkerAnnotation#getUnknownImageName(IMarker) */ protected String getUnknownImageName(IMarker marker) { return JavaPluginImages.IMG_OBJS_GHOST; } /** * Initializes the annotation's icon representation and its drawing layer * based upon the properties of the underlying marker. */ protected void initialize() { fQuickFixIconEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION); fImageType= NO_IMAGE; IMarker marker= getMarker(); if (MarkerUtilities.isMarkerType(marker, IBreakpoint.BREAKPOINT_MARKER)) { if (fPresentation == null) fPresentation= DebugUITools.newDebugModelPresentation(); setLayer(4); setImage(fPresentation.getImage(marker)); fImageType= BREAKPOINT_IMAGE; fType= AnnotationType.UNKNOWN; } else { fType= AnnotationType.UNKNOWN; try { if (marker.isSubtypeOf(IMarker.PROBLEM)) { int severity= marker.getAttribute(IMarker.SEVERITY, -1); switch (severity) { case IMarker.SEVERITY_ERROR: fType= AnnotationType.ERROR; break; case IMarker.SEVERITY_WARNING: fType= AnnotationType.WARNING; break; } } else if (marker.isSubtypeOf(IMarker.TASK)) fType= AnnotationType.TASK; else if (marker.isSubtypeOf(SearchUI.SEARCH_MARKER)) fType= AnnotationType.SEARCH; else if (marker.isSubtypeOf(IMarker.BOOKMARK)) fType= AnnotationType.BOOKMARK; } catch(CoreException e) { JavaPlugin.log(e); } super.initialize(); } } private boolean mustShowQuickFixIcon() { return fQuickFixIconEnabled && JavaCorrectionProcessor.hasCorrections(getMarker()); } private Image getQuickFixImage() { if (fgQuickFixImage == null) fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM); return fgQuickFixImage; } private Image getQuickFixErrorImage() { if (fgQuickFixErrorImage == null) fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR); return fgQuickFixErrorImage; } /* * @see IJavaAnnotation#getMessage() */ public String getMessage() { IMarker marker= getMarker(); if (marker == null) return ""; //$NON-NLS-1$ else return marker.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$ } /* * @see IJavaAnnotation#isTemporary() */ public boolean isTemporary() { return false; } /* * @see IJavaAnnotation#getArguments() */ public String[] getArguments() { if (isProblem()) return Util.getProblemArgumentsFromMarker(getMarker().getAttribute(IJavaModelMarker.ARGUMENTS, "")); //$NON-NLS-1$ return null; } /* * @see IJavaAnnotation#getId() */ public int getId() { if (isProblem()) return getMarker().getAttribute(IJavaModelMarker.ID, -1); return -1; } /* * @see IJavaAnnotation#isProblem() */ public boolean isProblem() { return fType == AnnotationType.WARNING || fType == AnnotationType.ERROR; } /* * @see IJavaAnnotation#isRelevant() */ public boolean isRelevant() { return !fNotRelevant; } /** * Overlays this annotation with the given javaAnnotation. * * @param javaAnnotation annotation that is overlaid by this annotation */ public void setOverlay(IJavaAnnotation javaAnnotation) { if (fOverlay != null) fOverlay.removeOverlaid(this); fOverlay= javaAnnotation; fNotRelevant= (fNotRelevant || fOverlay != null); if (javaAnnotation != null) javaAnnotation.addOverlaid(this); } /* * @see IJavaAnnotation#hasOverlay() */ public boolean hasOverlay() { return fOverlay != null; } /* * @see MarkerAnnotation#getImage(Display) */ public Image getImage(Display display) { if (fImageType == BREAKPOINT_IMAGE) return super.getImage(display); int newImageType= NO_IMAGE; if (hasOverlay()) newImageType= OVERLAY_IMAGE; else if (isRelevant()) { if (mustShowQuickFixIcon()) { if (fType == AnnotationType.ERROR) newImageType= QUICKFIX_ERROR_IMAGE; else newImageType= QUICKFIX_IMAGE; } else newImageType= ORIGINAL_MARKER_IMAGE; } else newImageType= GRAY_IMAGE; if (fImageType == newImageType && newImageType != OVERLAY_IMAGE) // Nothing changed - simply return the current image return super.getImage(display); Image newImage= null; switch (newImageType) { case ORIGINAL_MARKER_IMAGE: newImage= null; break; case OVERLAY_IMAGE: newImage= fOverlay.getImage(display); break; case QUICKFIX_IMAGE: newImage= getQuickFixImage(); break; case QUICKFIX_ERROR_IMAGE: newImage= getQuickFixErrorImage(); break; case GRAY_IMAGE: if (fImageType != ORIGINAL_MARKER_IMAGE) setImage(null); Image originalImage= super.getImage(display); if (originalImage != null) { ImageRegistry imageRegistry= getGrayMarkerImageRegistry(display); if (imageRegistry != null) { String key= Integer.toString(originalImage.hashCode()); Image grayImage= imageRegistry.get(key); if (grayImage == null) { grayImage= new Image(display, originalImage, SWT.IMAGE_GRAY); imageRegistry.put(key, grayImage); } newImage= grayImage; } } break; default: Assert.isLegal(false); } fImageType= newImageType; setImage(newImage); return super.getImage(display); } private ImageRegistry getGrayMarkerImageRegistry(Display display) { if (fgGrayMarkersImageRegistry == null) fgGrayMarkersImageRegistry= new ImageRegistry(display); return fgGrayMarkersImageRegistry; } /* * @see IJavaAnnotation#addOverlaid(IJavaAnnotation) */ public void addOverlaid(IJavaAnnotation annotation) { // not supported } /* * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation) */ public void removeOverlaid(IJavaAnnotation annotation) { // not supported } /* * @see IJavaAnnotation#getOverlaidIterator() */ public Iterator getOverlaidIterator() { // not supported return null; } /* * @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getAnnotationType() */ public AnnotationType getAnnotationType() { return fType; } }
29,531
Bug 29531 JavaColorManager initialized in non UI thread
Build I20030114 - open Workspace - select CU without opening in editor - activate Move refactoring - select different package - press Preview Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor (JavaColorManager.java:53) at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor (JavaColorManager.java:85) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.addToken (AbstractJavaScanner.java:90) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.initialize (AbstractJavaScanner.java:75) at org.eclipse.jdt.internal.ui.text.java.JavaCodeScanner.<init> (JavaCodeScanner.java:126) at org.eclipse.jdt.ui.text.JavaTextTools.<init>(JavaTextTools.java:80) at org.eclipse.jdt.internal.ui.JavaPlugin.getJavaTextTools (JavaPlugin.java:316) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider.initializ eDocument(CompilationUnitDocumentProvider.java:979) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider.createDoc ument(CompilationUnitDocumentProvider.java:994) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$BufferFac tory.internalGetDocument(CompilationUnitDocumentProvider.java:630) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider$BufferFac tory.createBuffer(CompilationUnitDocumentProvider.java:646) at org.eclipse.jdt.internal.core.WorkingCopy.openBuffer (WorkingCopy.java:365) at org.eclipse.jdt.internal.core.Openable.getBuffer(Openable.java:192) at org.eclipse.jdt.internal.core.CompilationUnit.getContents (CompilationUnit.java:367) at org.eclipse.jdt.internal.compiler.parser.Parser.parse (Parser.java:7095) at org.eclipse.jdt.internal.compiler.SourceElementParser.parseCompilationUnit (SourceElementParser.java:1051) at org.eclipse.jdt.internal.core.CompilationUnit.generateInfos (CompilationUnit.java:323) at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure (CompilationUnit.java:77) at org.eclipse.jdt.internal.core.Openable.openWhenClosed (Openable.java:395) at org.eclipse.jdt.internal.core.Openable.open(Openable.java:346) at org.eclipse.jdt.internal.core.WorkingCopy.open(WorkingCopy.java:354) at org.eclipse.jdt.internal.core.CompilationUnit.getWorkingCopy (CompilationUnit.java:609) at org.eclipse.jdt.internal.core.CompilationUnit.getSharedWorkingCopy (CompilationUnit.java:581) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider.createEle mentInfo(CompilationUnitDocumentProvider.java:845) at org.eclipse.ui.texteditor.AbstractDocumentProvider.connect (AbstractDocumentProvider.java:302) at org.eclipse.jdt.internal.corext.textmanipulation.TextBufferFactory.acquire (TextBufferFactory.java:85) at org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer.acquire (TextBuffer.java:371) at org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure.aquireTextBuff er(ImportsStructure.java:538) at org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure.<init> (ImportsStructure.java:85) at org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit.<init> (ImportEdit.java:33) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.getImportE dit(MoveCuUpdateCreator.java:217) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.addImportT oSourcePackageTypes(MoveCuUpdateCreator.java:176) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.addUpdates (MoveCuUpdateCreator.java:121) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.addUpdates (MoveCuUpdateCreator.java:112) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveCuUpdateCreator.createChan geManager(MoveCuUpdateCreator.java:88) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.createChangeMa nager(MoveRefactoring.java:448) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.checkInput (MoveRefactoring.java:151) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
resolved fixed
df800ea
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T19:05:14Z
2003-01-15T14:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/AbstractJavaScanner.java
package org.eclipse.jdt.internal.ui.text; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.StringConverter; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; import org.eclipse.jface.text.rules.IRule; import org.eclipse.jface.text.rules.Token; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jdt.ui.text.IColorManager; import org.eclipse.jdt.ui.text.IColorManagerExtension; /** * Initialized with a color manager and a preference store, its subclasses are * only responsible for providing a list of preference keys based on which tokens * are generated and to use this tokens to define the rules controlling this scanner. */ public abstract class AbstractJavaScanner extends BufferedRuleBasedScanner { private IColorManager fColorManager; private IPreferenceStore fPreferenceStore; private Map fTokenMap= new HashMap(); private String[] fPropertyNamesColor; private String[] fPropertyNamesStyle; /** * Returns the list of preference keys which define the tokens * used in the rules of this scanner. */ abstract protected String[] getTokenProperties(); /** * Creates the list of rules controlling this scanner. */ abstract protected List createRules(); /** * Creates an abstract Java scanner. */ public AbstractJavaScanner(IColorManager manager, IPreferenceStore store) { super(); fColorManager= manager; fPreferenceStore= store; } /** * Must be called after the constructor has been called. */ public final void initialize() { fPropertyNamesColor= getTokenProperties(); int length= fPropertyNamesColor.length; fPropertyNamesStyle= new String[length]; for (int i= 0; i < length; i++) { fPropertyNamesStyle[i]= fPropertyNamesColor[i] + "_bold"; //$NON-NLS-1$ addToken(fPropertyNamesColor[i], fPropertyNamesStyle[i]); } initializeRules(); } private void addToken(String colorKey, String styleKey) { RGB rgb= PreferenceConverter.getColor(fPreferenceStore, colorKey); if (fColorManager instanceof IColorManagerExtension) { IColorManagerExtension ext= (IColorManagerExtension) fColorManager; ext.unbindColor(colorKey); ext.bindColor(colorKey, rgb); } boolean bold= fPreferenceStore.getBoolean(styleKey); fTokenMap.put(colorKey, new Token(new TextAttribute(fColorManager.getColor(colorKey), null, bold ? SWT.BOLD : SWT.NORMAL))); } protected Token getToken(String key) { return (Token) fTokenMap.get(key); } private void initializeRules() { List rules= createRules(); if (rules != null) { IRule[] result= new IRule[rules.size()]; rules.toArray(result); setRules(result); } } private int indexOf(String property) { if (property != null) { int length= fPropertyNamesColor.length; for (int i= 0; i < length; i++) { if (property.equals(fPropertyNamesColor[i]) || property.equals(fPropertyNamesStyle[i])) return i; } } return -1; } public boolean affectsBehavior(PropertyChangeEvent event) { return indexOf(event.getProperty()) >= 0; } public void adaptToPreferenceChange(PropertyChangeEvent event) { String p= event.getProperty(); int index= indexOf(p); Token token= getToken(fPropertyNamesColor[index]); if (fPropertyNamesColor[index].equals(p)) adaptToColorChange(token, event); else adaptToStyleChange(token, event); } private void adaptToColorChange(Token token, PropertyChangeEvent event) { RGB rgb= null; Object value= event.getNewValue(); if (value instanceof RGB) rgb= (RGB) value; else if (value instanceof String) rgb= StringConverter.asRGB((String) value); if (rgb != null) { String property= event.getProperty(); if (fColorManager instanceof IColorManagerExtension) { IColorManagerExtension ext= (IColorManagerExtension) fColorManager; ext.unbindColor(property); ext.bindColor(property, rgb); } Object data= token.getData(); if (data instanceof TextAttribute) { TextAttribute oldAttr= (TextAttribute) data; token.setData(new TextAttribute(fColorManager.getColor(property), oldAttr.getBackground(), oldAttr.getStyle())); } } } private void adaptToStyleChange(Token token, PropertyChangeEvent event) { boolean bold= false; Object value= event.getNewValue(); if (value instanceof Boolean) bold= ((Boolean) value).booleanValue(); else if (value instanceof String) { String s= (String) value; if (IPreferenceStore.TRUE.equals(s)) bold= true; else if (IPreferenceStore.FALSE.equals(s)) bold= false; } Object data= token.getData(); if (data instanceof TextAttribute) { TextAttribute oldAttr= (TextAttribute) data; boolean isBold= (oldAttr.getStyle() == SWT.BOLD); if (isBold != bold) token.setData(new TextAttribute(oldAttr.getForeground(), oldAttr.getBackground(), bold ? SWT.BOLD : SWT.NORMAL)); } } }
20,666
Bug 20666 Export JavaDoc should examine jdk compliance
The Export Javadoc wizard should examine the jdk1.3/jdk1.4 compliance for a project and add the appropriate javadoc switch by default to the javadoc args viewer. Result of not fixing: Javadoc users will get errors in the console complaining about all their assert statements, and then have to figure out the switches to add to correct this problem.
resolved fixed
2c506ba
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T19:23:18Z
2002-06-19T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocOptionsManager.java
/* * Copyright (c) 2002 IBM Corp. All rights reserved. * This file is made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html */ package org.eclipse.jdt.internal.ui.javadocexport; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.DialogSettings; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.launching.ExecutionArguments; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage; public class JavadocOptionsManager { private IWorkspaceRoot fRoot; //consider making a List private List fProjects; private IFile fXmlfile; private StatusInfo fWizardStatus; private List fSourceElements; private List fSelectedElements; private String fAccess; private String fDocletpath; private String fDocletname; private boolean fFromStandard; private String fStylesheet; private String fAdditionalParams; private String fOverview; private String fTitle; private String fJDocCommand; private IPath[] fSourcepath; private IPath[] fClasspath; private boolean fNotree; private boolean fNoindex; private boolean fSplitindex; private boolean fNonavbar; private boolean fNodeprecated; private boolean fNoDeprecatedlist; private boolean fAuthor; private boolean fVersion; private boolean fUse; private boolean fOpenInBrowser; //list of hrefs in string format private Map fLinks; //add-on for multi-project version private String fDestination; private String fDependencies; private String fAntpath; public final String PRIVATE= "private"; //$NON-NLS-1$ public final String PROTECTED= "protected"; //$NON-NLS-1$ public final String PACKAGE= "package"; //$NON-NLS-1$ public final String PUBLIC= "public"; //$NON-NLS-1$ public final String USE= "use"; //$NON-NLS-1$ public final String NOTREE= "notree"; //$NON-NLS-1$ public final String NOINDEX= "noindex"; //$NON-NLS-1$ public final String NONAVBAR= "nonavbar"; //$NON-NLS-1$ public final String NODEPRECATED= "nodeprecated"; //$NON-NLS-1$ public final String NODEPRECATEDLIST= "nodeprecatedlist"; //$NON-NLS-1$ public final String VERSION= "version"; //$NON-NLS-1$ public final String AUTHOR= "author"; //$NON-NLS-1$ public final String SPLITINDEX= "splitindex"; //$NON-NLS-1$ public final String STYLESHEETFILE= "stylesheetfile"; //$NON-NLS-1$ public final String OVERVIEW= "overview"; //$NON-NLS-1$ public final String DOCLETNAME= "docletname"; //$NON-NLS-1$ public final String DOCLETPATH= "docletpath"; //$NON-NLS-1$ public final String SOURCEPATH= "sourcepath"; //$NON-NLS-1$ public final String CLASSPATH= "classpath"; //$NON-NLS-1$ public final String DESTINATION= "destdir"; //$NON-NLS-1$ public final String OPENINBROWSER= "openinbrowser"; //$NON-NLS-1$ public final String VISIBILITY= "access"; //$NON-NLS-1$ public final String PACKAGENAMES= "packagenames"; //$NON-NLS-1$ public final String SOURCEFILES= "sourcefiles"; //$NON-NLS-1$ public final String EXTRAOPTIONS= "additionalparam"; //$NON-NLS-1$ public final String JAVADOCCOMMAND= "javadoccommand"; //$NON-NLS-1$ public final String TITLE= "doctitle"; //$NON-NLS-1$ public final String HREF= "href"; //$NON-NLS-1$ public final String NAME= "name"; //$NON-NLS-1$ public final String PATH= "path"; //$NON-NLS-1$ private final String FROMSTANDARD= "fromStandard"; //$NON-NLS-1$ private final String ANTPATH= "antpath"; //$NON-NLS-1$ /** * @param xmlJavadocFile The ant file to take initl values from or null, if not started from an ant file. * @param setting Dialog settings for the Javadoc exporter. */ public JavadocOptionsManager(IFile xmlJavadocFile, IDialogSettings settings, ISelection currSelection) { Element element; this.fRoot= ResourcesPlugin.getWorkspace().getRoot(); fJDocCommand= JavadocPreferencePage.getJavaDocCommand(); this.fXmlfile= xmlJavadocFile; this.fWizardStatus= new StatusInfo(); this.fLinks= new HashMap(); fProjects= new ArrayList(); if (xmlJavadocFile != null) { try { JavadocReader reader= new JavadocReader(xmlJavadocFile.getContents()); element= reader.readXML(); IJavaProject p= reader.getProject(); if (element == null || p == null) { fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$ loadStore(settings, currSelection); } else { fProjects.add(p); loadStore(element, settings); } } catch (CoreException e) { JavaPlugin.log(e); fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$ loadStore(settings, currSelection); } catch (IOException e) { JavaPlugin.log(e); fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectIOE.warning")); //$NON-NLS-1$ loadStore(settings, currSelection); } catch (SAXException e) { fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectSAXE.warning")); //$NON-NLS-1$ loadStore(settings, currSelection); } } else loadStore(settings, currSelection); } private void loadStore(IDialogSettings settings, ISelection sel) { if (settings != null) { //getValidSelection will also find the project fSelectedElements= getValidSelection(sel); fAccess= settings.get(VISIBILITY); if (fAccess == null) fAccess= PROTECTED; //this is defaulted to false. fFromStandard= settings.getBoolean(FROMSTANDARD); //doclet is loaded even if the standard doclet is being used fDocletpath= settings.get(DOCLETPATH); fDocletname= settings.get(DOCLETNAME); if (fDocletpath == null || fDocletname == null) { fFromStandard= true; fDocletpath= ""; //$NON-NLS-1$ fDocletname= ""; //$NON-NLS-1$ } //load a default antpath fAntpath= settings.get(ANTPATH); if (fAntpath == null) fAntpath= ""; //$NON-NLS-1$ //$NON-NLS-1$ //load a default antpath fDestination= settings.get(DESTINATION); if (fDestination == null) fDestination= ""; //$NON-NLS-1$ //$NON-NLS-1$ fTitle= settings.get(TITLE); if (fTitle == null) fTitle= ""; //$NON-NLS-1$ fStylesheet= settings.get(STYLESHEETFILE); if (fStylesheet == null) fStylesheet= ""; //$NON-NLS-1$ fAdditionalParams= settings.get(EXTRAOPTIONS); if (fAdditionalParams == null) fAdditionalParams= ""; //$NON-NLS-1$ fOverview= settings.get(OVERVIEW); if (fOverview == null) fOverview= ""; //$NON-NLS-1$ fUse= loadbutton(settings.get(USE)); fAuthor= loadbutton(settings.get(AUTHOR)); fVersion= loadbutton(settings.get(VERSION)); fNodeprecated= loadbutton(settings.get(NODEPRECATED)); fNoDeprecatedlist= loadbutton(settings.get(NODEPRECATEDLIST)); fNonavbar= loadbutton(settings.get(NONAVBAR)); fNoindex= loadbutton(settings.get(NOINDEX)); fNotree= loadbutton(settings.get(NOTREE)); fSplitindex= loadbutton(settings.get(SPLITINDEX)); fOpenInBrowser= loadbutton(settings.get(OPENINBROWSER)); //get the set of project specific data loadLinksFromDialogSettings(settings); } else loadDefaults(sel); } private String getDefaultAntPath(IJavaProject project) { if (project != null) { IPath path= project.getProject().getLocation(); if (path != null) return path.append("javadoc.xml").toOSString(); //$NON-NLS-1$ } return ""; //$NON-NLS-1$ } private String getDefaultDestination(IJavaProject project) { if (project != null) { URL url= JavaUI.getProjectJavadocLocation(project); //uses default if source is has http protocol if (url == null || !url.getProtocol().equals("file")) { //$NON-NLS-1$ IPath path= project.getProject().getLocation(); if (path != null) return path.append("doc").toOSString(); //$NON-NLS-1$ } else { //must do this to remove leading "/" return (new File(url.getFile())).getPath(); } } return ""; //$NON-NLS-1$ } /** * Method creates a list of data structes that contain * The destination, antfile location and the list of library/project references for every * project in the workspace.Defaults are created for new project. */ private void loadLinksFromDialogSettings(IDialogSettings settings) { //sets data for projects if stored in the dialog settings if (settings != null) { IDialogSettings links= settings.getSection("projects"); //$NON-NLS-1$ if (links != null) { IDialogSettings[] projs= links.getSections(); for (int i= 0; i < projs.length; i++) { IDialogSettings iDialogSettings= projs[i]; String projectName= iDialogSettings.getName(); IProject project= fRoot.getProject(projectName); //make sure project has not been removed if (project.exists()) { IJavaProject javaProject= JavaCore.create(project); if (!fLinks.containsKey(javaProject)) { String hrefs= iDialogSettings.get(HREF); if (hrefs == null) { hrefs= ""; //$NON-NLS-1$ } String destdir= iDialogSettings.get(DESTINATION); if (destdir == null || destdir.length() == 0) { destdir= getDefaultDestination(javaProject); } String antpath= iDialogSettings.get(ANTPATH); if (antpath == null || antpath.length() == 0) { antpath= getDefaultAntPath(javaProject); } ProjectData data= new ProjectData(javaProject); data.setDestination(destdir); data.setAntpath(antpath); data.setlinks(hrefs); if (!fLinks.containsValue(javaProject)) fLinks.put(javaProject, data); } } } } } //finds projects in the workspace that have been added since the //last time the wizard was run IProject[] projects= fRoot.getProjects(); for (int i= 0; i < projects.length; i++) { IProject iProject= projects[i]; IJavaProject javaProject= JavaCore.create(iProject); if (!fLinks.containsKey(javaProject)) { ProjectData data= new ProjectData(javaProject); data.setDestination(getDefaultDestination(javaProject)); data.setAntpath(getDefaultAntPath(javaProject)); data.setlinks(""); //$NON-NLS-1$ fLinks.put(javaProject, data); } } } //loads defaults for wizard (nothing is stored) private void loadDefaults(ISelection sel) { fSelectedElements= getValidSelection(sel); fAccess= PUBLIC; fDocletname= ""; //$NON-NLS-1$ fDocletpath= ""; //$NON-NLS-1$ fTitle= ""; //$NON-NLS-1$ fStylesheet= ""; //$NON-NLS-1$ fAdditionalParams= ""; //$NON-NLS-1$ fOverview= ""; //$NON-NLS-1$ fAntpath= ""; //$NON-NLS-1$ fDestination= ""; //$NON-NLS-1$ fUse= true; fAuthor= true; fVersion= true; fNodeprecated= false; fNoDeprecatedlist= false; fNonavbar= false; fNoindex= false; fNotree= false; fSplitindex= true; fOpenInBrowser= false; //by default it is empty all project map to the empty string fFromStandard= true; loadLinksFromDialogSettings(null); } private void loadStore(Element element, IDialogSettings settings) { fAccess= element.getAttribute(VISIBILITY); if (!(fAccess.length() > 0)) fAccess= PROTECTED; //Since the selected packages are stored we must locate the project String destination= element.getAttribute(DESTINATION); fDestination= destination; fFromStandard= true; fDocletname= ""; //$NON-NLS-1$ fDocletpath= ""; //$NON-NLS-1$ if (destination.equals("")) { //$NON-NLS-1$ NodeList list= element.getChildNodes(); for (int i= 0; i < list.getLength(); i++) { Node child= list.item(i); if (child.getNodeName().equals("doclet")) { //$NON-NLS-1$ fDocletpath= ((Element) child).getAttribute(PATH); fDocletname= ((Element) child).getAttribute(NAME); if (!(fDocletpath.equals("") && !fDocletname.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$ fFromStandard= false; } else { fDocletname= ""; //$NON-NLS-1$ fDocletpath= ""; //$NON-NLS-1$ } break; } } } //find all the links stored in the ant script boolean firstTime= true; StringBuffer buf= new StringBuffer(); NodeList children= element.getChildNodes(); for (int i= 0; i < children.getLength(); i++) { Node child= children.item(i); if (child.getNodeName().equals("link")) { //$NON-NLS-1$ String href= ((Element) child).getAttribute(HREF); if (firstTime) firstTime= false; else buf.append(';'); buf.append(href); } } //associate all those links with each project selected for (Iterator iter= fProjects.iterator(); iter.hasNext();) { IJavaProject iJavaProject= (IJavaProject) iter.next(); ProjectData data= new ProjectData(iJavaProject); IPath path= fXmlfile.getLocation(); if (path != null) data.setAntpath(path.toOSString()); else data.setAntpath(""); //$NON-NLS-1$ data.setlinks(buf.toString()); data.setDestination(destination); fLinks.put(iJavaProject, data); } //get tree elements setSelectedElementsFromAnt(element, (IJavaProject) fProjects.get(0)); IPath p= fXmlfile.getLocation(); if (p != null) fAntpath= p.toOSString(); else fAntpath= ""; //$NON-NLS-1$ fStylesheet= element.getAttribute(STYLESHEETFILE); fTitle= element.getAttribute(TITLE); fAdditionalParams= element.getAttribute(EXTRAOPTIONS); fOverview= element.getAttribute(OVERVIEW); fUse= loadbutton(element.getAttribute(USE)); fAuthor= loadbutton(element.getAttribute(AUTHOR)); fVersion= loadbutton(element.getAttribute(VERSION)); fNodeprecated= loadbutton(element.getAttribute(NODEPRECATED)); fNoDeprecatedlist= loadbutton(element.getAttribute(NODEPRECATEDLIST)); fNonavbar= loadbutton(element.getAttribute(NONAVBAR)); fNoindex= loadbutton(element.getAttribute(NOINDEX)); fNotree= loadbutton(element.getAttribute(NOTREE)); fSplitindex= loadbutton(element.getAttribute(SPLITINDEX)); } /* * Method creates an absolute path to the project. If the path is already * absolute it returns the path. If it encounters any difficulties in * creating the absolute path, the method returns null. * * @param pathStr * @return IPath */ private IPath makeAbsolutePathFromRelative(String pathStr) { IPath path= new Path(pathStr); if (!path.isAbsolute()) { if (fXmlfile == null) { return null; } IPath basePath= fXmlfile.getParent().getLocation(); // relative to the ant file location if (basePath == null) { return null; } return basePath.append(pathStr); } return path; } private void setSelectedElementsFromAnt(Element element, IJavaProject iJavaProject) { fSelectedElements= new ArrayList(); //get all the packages in side the project String name; String packagenames= element.getAttribute(PACKAGENAMES); if (packagenames != null) { StringTokenizer tokenizer= new StringTokenizer(packagenames, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { name= tokenizer.nextToken().trim(); IJavaElement el; try { el= JavaModelUtil.findTypeContainer(iJavaProject, name); } catch (JavaModelException e) { JavaPlugin.log(e); continue; } if ((el != null) && (el instanceof IPackageFragment)) { fSelectedElements.add(el); } } } //get all CompilationUnites in side the project String sourcefiles= element.getAttribute(SOURCEFILES); if (sourcefiles != null) { StringTokenizer tokenizer= new StringTokenizer(sourcefiles, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { name= tokenizer.nextToken().trim(); if (name.endsWith(".java")) { //$NON-NLS-1$ IPath path= makeAbsolutePathFromRelative(name); //if unable to create an absolute path the the resource skip it if (path == null) continue; IFile[] files= fRoot.findFilesForLocation(path); for (int i= 0; i < files.length; i++) { IFile curr= files[i]; if (curr.getProject().equals(iJavaProject.getProject())) { IJavaElement el= JavaCore.createCompilationUnitFrom(curr); if (el != null) { fSelectedElements.add(el); } } } } } } } //it is possible that the package list is empty public StatusInfo getWizardStatus() { return fWizardStatus; } public IJavaElement[] getSelectedElements() { return (IJavaElement[]) fSelectedElements.toArray(new IJavaElement[fSelectedElements.size()]); } public IJavaElement[] getSourceElements() { return (IJavaElement[]) fSourceElements.toArray(new IJavaElement[fSourceElements.size()]); } public String getAccess() { return fAccess; } public String getGeneralAntpath() { return fAntpath; } public String getSpecificAntpath(IJavaProject project) { ProjectData data= (ProjectData) fLinks.get(project); if (data != null) return data.getAntPath(); else return ""; //$NON-NLS-1$ } public boolean fromStandard() { return fFromStandard; } //for now if multiple projects are selected the destination //feild will be empty, public String getDestination(IJavaProject project) { ProjectData data= (ProjectData) fLinks.get(project); if (data != null) return data.getDestination(); else return ""; //$NON-NLS-1$ } public String getDestination() { return fDestination; } public String getDocletPath() { return fDocletpath; } public String getDocletName() { return fDocletname; } public String getStyleSheet() { return fStylesheet; } public String getOverview() { return fOverview; } public String getAdditionalParams() { return fAdditionalParams; } public IPath[] getClasspath() { return fClasspath; } public IPath[] getSourcepath() { return fSourcepath; } public IWorkspaceRoot getRoot() { return fRoot; } // public IJavaProject[] getJavaProjects() { // return (IJavaProject[]) fProjects.toArray(new IJavaProject[fProjects.size()]); // } //Use only this one later public List getJavaProjects() { return fProjects; } public String getTitle() { return fTitle; } public String getLinks(IJavaProject project) { ProjectData data= (ProjectData) fLinks.get(project); if (data != null) return data.getlinks(); else return ""; //$NON-NLS-1$ } public String getDependencies() { return fDependencies; } public Map getLinkMap() { return fLinks; } public boolean doOpenInBrowser() { return fOpenInBrowser; } public boolean getBoolean(String flag) { if (flag.equals(AUTHOR)) return fAuthor; else if (flag.equals(VERSION)) return fVersion; else if (flag.equals(USE)) return fUse; else if (flag.equals(NODEPRECATED)) return fNodeprecated; else if (flag.equals(NODEPRECATEDLIST)) return fNoDeprecatedlist; else if (flag.equals(NOINDEX)) return fNoindex; else if (flag.equals(NOTREE)) return fNotree; else if (flag.equals(SPLITINDEX)) return fSplitindex; else if (flag.equals(NONAVBAR)) return fNonavbar; else return false; } private boolean loadbutton(String value) { if (value == null || value.equals("")) //$NON-NLS-1$ return false; else { if (value.equals("true")) //$NON-NLS-1$ return true; else return false; } } private String flatPathList(IPath[] paths) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < paths.length; i++) { if (i > 0) { buf.append(File.pathSeparatorChar); } buf.append(paths[i].toOSString()); } return buf.toString(); } public String[] createArgumentArray() throws CoreException { if (fProjects.isEmpty()) { return new String[0]; } List args= new ArrayList(); args.add(fJDocCommand); if (fFromStandard) { args.add("-d"); //$NON-NLS-1$ args.add(fDestination); } else { if (!fAdditionalParams.equals("")) { //$NON-NLS-1$ ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$ String[] argsArray= tokens.getProgramArgumentsArray(); for (int i= 0; i < argsArray.length; i++) { args.add(argsArray[i]); } } args.add("-doclet"); //$NON-NLS-1$ args.add(fDocletname); args.add("-docletpath"); //$NON-NLS-1$ args.add(fDocletpath); } args.add("-sourcepath"); //$NON-NLS-1$ args.add(flatPathList(fSourcepath)); args.add("-classpath"); //$NON-NLS-1$ args.add(flatPathList(fClasspath)); args.add("-" + fAccess); //$NON-NLS-1$ if (fFromStandard) { if (fUse) args.add("-use"); //$NON-NLS-1$ if (fVersion) args.add("-version"); //$NON-NLS-1$ if (fAuthor) args.add("-author"); //$NON-NLS-1$ if (fNonavbar) args.add("-nonavbar"); //$NON-NLS-1$ if (fNoindex) args.add("-noindex"); //$NON-NLS-1$ if (fNotree) args.add("-notree"); //$NON-NLS-1$ if (fNodeprecated) args.add("-nodeprecated"); //$NON-NLS-1$ if (fNoDeprecatedlist) args.add("-nodeprecatedlist"); //$NON-NLS-1$ if (fSplitindex) args.add("-splitindex"); //$NON-NLS-1$ if (!fTitle.equals("")) { //$NON-NLS-1$ args.add("-doctitle"); //$NON-NLS-1$ args.add(fTitle); } if (!fStylesheet.equals("")) { //$NON-NLS-1$ args.add("-stylesheetfile"); //$NON-NLS-1$ args.add(fStylesheet); } if (!fAdditionalParams.equals("")) { //$NON-NLS-1$ ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$ String[] argsArray= tokens.getProgramArgumentsArray(); for (int i= 0; i < argsArray.length; i++) { args.add(argsArray[i]); } } String hrefs= (String) fDependencies; StringTokenizer tokenizer= new StringTokenizer(hrefs, ";"); //$NON-NLS-1$ while (tokenizer.hasMoreElements()) { String href= (String) tokenizer.nextElement(); args.add("-link"); //$NON-NLS-1$ args.add(href); } } //end standard options if (!fOverview.equals("")) { //$NON-NLS-1$ args.add("-overview"); //$NON-NLS-1$ args.add(fOverview); } for (int i= 0; i < fSourceElements.size(); i++) { IJavaElement curr= (IJavaElement) fSourceElements.get(i); if (curr instanceof IPackageFragment) { args.add(curr.getElementName()); } else if (curr instanceof ICompilationUnit) { IPath p= curr.getResource().getLocation(); if (p != null) args.add(p.toOSString()); } } String[] res= (String[]) args.toArray(new String[args.size()]); return res; } public void createXML() { FileOutputStream objectStreamOutput= null; //@change //for now only writting ant files for single project selection String antpath= fAntpath; try { if (!antpath.equals("")) { //$NON-NLS-1$ File file= new File(antpath); IPath antPath= new Path(antpath); IPath antDir= antPath.removeLastSegments(1); IPath basePath= null; Assert.isTrue(fProjects.size() == 1); IJavaProject jproject= (IJavaProject) fProjects.get(0); IWorkspaceRoot root= jproject.getProject().getWorkspace().getRoot(); if (root.findFilesForLocation(antPath).length > 0) { basePath= antDir; // only do relative path if ant file is stored in the workspace } antDir.toFile().mkdirs(); objectStreamOutput= new FileOutputStream(file); JavadocWriter writer= new JavadocWriter(objectStreamOutput, basePath, jproject); writer.writeXML(this); } } catch (IOException e) { JavaPlugin.log(e); } catch (CoreException e) { JavaPlugin.log(e); } finally { if (objectStreamOutput != null) { try { objectStreamOutput.close(); } catch (IOException e) { } } } } public IDialogSettings createDialogSettings() { IDialogSettings settings= new DialogSettings("javadoc"); //$NON-NLS-1$ settings.put(FROMSTANDARD, fFromStandard); settings.put(DOCLETNAME, fDocletname); settings.put(DOCLETPATH, fDocletpath); settings.put(VISIBILITY, fAccess); settings.put(USE, fUse); settings.put(AUTHOR, fAuthor); settings.put(VERSION, fVersion); settings.put(NODEPRECATED, fNodeprecated); settings.put(NODEPRECATEDLIST, fNoDeprecatedlist); settings.put(SPLITINDEX, fSplitindex); settings.put(NOINDEX, fNoindex); settings.put(NOTREE, fNotree); settings.put(NONAVBAR, fNonavbar); settings.put(OPENINBROWSER, fOpenInBrowser); if (!fAntpath.equals("")) //$NON-NLS-1$ settings.put(ANTPATH, fAntpath); if (!fDestination.equals("")) //$NON-NLS-1$ settings.put(DESTINATION, fDestination); if (!fAdditionalParams.equals("")) //$NON-NLS-1$ settings.put(EXTRAOPTIONS, fAdditionalParams); if (!fOverview.equals("")) //$NON-NLS-1$ settings.put(OVERVIEW, fOverview); if (!fStylesheet.equals("")) //$NON-NLS-1$ settings.put(STYLESHEETFILE, fStylesheet); if (!fTitle.equals("")) //$NON-NLS-1$ settings.put(TITLE, fTitle); IDialogSettings links= new DialogSettings("projects"); //$NON-NLS-1$ //Write all project information to DialogSettings. Set keys= fLinks.keySet(); for (Iterator iter= keys.iterator(); iter.hasNext();) { IJavaProject iJavaProject= (IJavaProject) iter.next(); IDialogSettings proj= new DialogSettings(iJavaProject.getElementName()); if (!keys.contains(iJavaProject)) { proj.put(HREF, ""); //$NON-NLS-1$ proj.put(DESTINATION, ""); //$NON-NLS-1$ proj.put(ANTPATH, ""); //$NON-NLS-1$ } else { ProjectData data= (ProjectData) fLinks.get(iJavaProject); proj.put(HREF, data.getlinks()); proj.put(DESTINATION, data.getDestination()); proj.put(ANTPATH, data.getAntPath()); } links.addSection(proj); } settings.addSection(links); return settings; } public void setAccess(String access) { this.fAccess= access; } public void setDestination(IJavaProject project, String destination) { ProjectData data= (ProjectData) fLinks.get(project); if (data != null) data.setDestination(destination); } public void setDestination(String destination) { fDestination= destination; } public void setDocletPath(String docletpath) { this.fDocletpath= docletpath; } public void setDocletName(String docletname) { this.fDocletname= docletname; } public void setStyleSheet(String stylesheet) { this.fStylesheet= stylesheet; } public void setOverview(String overview) { this.fOverview= overview; } public void setAdditionalParams(String params) { fAdditionalParams= params; } public void setSpecificAntpath(IJavaProject project, String antpath) { ProjectData data= (ProjectData) fLinks.get(project); if (data != null) data.setAntpath(antpath); } public void setGeneralAntpath(String antpath) { this.fAntpath= antpath; } public void setClasspath(IPath[] classpath) { this.fClasspath= classpath; } public void setSourcepath(IPath[] sourcepath) { this.fSourcepath= sourcepath; } public void setSourceElements(IJavaElement[] elements) { this.fSourceElements= new ArrayList(Arrays.asList(elements)); } public void setRoot(IWorkspaceRoot root) { this.fRoot= root; } public void setProjects(IJavaProject[] projects, boolean clear) { if (clear) fProjects.clear(); for (int i= 0; i < projects.length; i++) { IJavaProject iJavaProject= projects[i]; if (!fProjects.contains(iJavaProject)) this.fProjects.add(iJavaProject); } } public void setFromStandard(boolean fromStandard) { this.fFromStandard= fromStandard; } public void setTitle(String title) { this.fTitle= title; } public void setDependencies(String dependencies) { fDependencies= dependencies; } public void setLinks(IJavaProject project, String hrefs) { ProjectData data= (ProjectData) fLinks.get(project); if (data != null) data.setlinks(hrefs); } public void setOpenInBrowser(boolean openInBrowser) { this.fOpenInBrowser= openInBrowser; } public void setBoolean(String flag, boolean value) { if (flag.equals(AUTHOR)) this.fAuthor= value; else if (flag.equals(USE)) this.fUse= value; else if (flag.equals(VERSION)) this.fVersion= value; else if (flag.equals(NODEPRECATED)) this.fNodeprecated= value; else if (flag.equals(NODEPRECATEDLIST)) this.fNoDeprecatedlist= value; else if (flag.equals(NOINDEX)) this.fNoindex= value; else if (flag.equals(NOTREE)) this.fNotree= value; else if (flag.equals(SPLITINDEX)) this.fSplitindex= value; else if (flag.equals(NONAVBAR)) this.fNonavbar= value; } private List getValidSelection(ISelection currentSelection) { ArrayList res= new ArrayList(); if (currentSelection instanceof IStructuredSelection) { IStructuredSelection structuredSelection= (IStructuredSelection) currentSelection; if (structuredSelection.isEmpty()) { currentSelection= JavaPlugin.getActiveWorkbenchWindow().getSelectionService().getSelection(); if (currentSelection instanceof IStructuredSelection) structuredSelection= (IStructuredSelection) currentSelection; } Iterator iter= structuredSelection.iterator(); //this method will also find the project for default //destination and ant generation paths getProjects(res, iter); } return res; } private void getProjects(List selectedElements, Iterator iter) { while (iter.hasNext()) { Object selectedElement= iter.next(); IJavaElement elem= getSelectableJavaElement(selectedElement); if (elem != null) { IJavaProject jproj= elem.getJavaProject(); if (jproj != null) { //adding the project of the selected element in the list //now we can select and generate javadoc for two //methods in different projects if (!fProjects.contains(jproj)) fProjects.add(jproj); selectedElements.add(elem); } } } //if no projects selected add a default if (fProjects.isEmpty()) { try { IJavaProject[] jprojects= JavaCore.create(fRoot).getJavaProjects(); for (int i= 0; i < jprojects.length; i++) { IJavaProject iJavaProject= jprojects[i]; if (getValidProject(iJavaProject)) { fProjects.add(iJavaProject); break; } } } catch (JavaModelException e) { JavaPlugin.log(e); } } } private IJavaElement getSelectableJavaElement(Object obj) { IJavaElement je= null; try { if (obj instanceof IAdaptable) { je= (IJavaElement) ((IAdaptable) obj).getAdapter(IJavaElement.class); } if (je == null) { return null; } switch (je.getElementType()) { case IJavaElement.JAVA_MODEL : case IJavaElement.JAVA_PROJECT : case IJavaElement.CLASS_FILE : break; case IJavaElement.PACKAGE_FRAGMENT_ROOT : if (containsCompilationUnits((IPackageFragmentRoot) je)) { return je; } break; case IJavaElement.PACKAGE_FRAGMENT : if (containsCompilationUnits((IPackageFragment) je)) { return je; } break; default : ICompilationUnit cu= (ICompilationUnit) je.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } return cu; } } } catch (JavaModelException e) { JavaPlugin.log(e); } IJavaProject project= je.getJavaProject(); if (getValidProject(project)) return project; else return null; } private boolean getValidProject(IJavaProject project) { if (project != null) { try { IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { if (containsCompilationUnits(roots[i])) { return true; } } } catch (JavaModelException e) { JavaPlugin.log(e); } } return false; } private boolean containsCompilationUnits(IPackageFragmentRoot root) throws JavaModelException { if (root.getKind() != IPackageFragmentRoot.K_SOURCE) { return false; } IJavaElement[] elements= root.getChildren(); for (int i= 0; i < elements.length; i++) { if (elements[i] instanceof IPackageFragment) { IPackageFragment fragment= (IPackageFragment) elements[i]; if (containsCompilationUnits(fragment)) { return true; } } } return false; } private boolean containsCompilationUnits(IPackageFragment pack) throws JavaModelException { return pack.getCompilationUnits().length > 0; } private class ProjectData { private IJavaProject dataProject; private String dataHrefs; private String dataDestdir; private String dataAntPath; ProjectData(IJavaProject project) { dataProject= project; } public void setlinks(String hrefs) { if (hrefs == null) dataHrefs= ""; //$NON-NLS-1$ else dataHrefs= hrefs; } public void setDestination(String destination) { if (destination == null) dataDestdir= ""; //$NON-NLS-1$ else dataDestdir= destination; } public void setAntpath(String antpath) { if (antpath == null) dataAntPath= ""; //$NON-NLS-1$ else dataAntPath= antpath; } public String getlinks() { return dataHrefs; } public String getDestination() { return dataDestdir; } public String getAntPath() { return dataAntPath; } } }
20,666
Bug 20666 Export JavaDoc should examine jdk compliance
The Export Javadoc wizard should examine the jdk1.3/jdk1.4 compliance for a project and add the appropriate javadoc switch by default to the javadoc args viewer. Result of not fixing: Javadoc users will get errors in the console complaining about all their assert statements, and then have to figure out the switches to add to correct this problem.
resolved fixed
2c506ba
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T19:23:18Z
2002-06-19T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.javadocexport; import java.io.File; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.events.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.Control; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.SWTUtil; public class JavadocSpecificsWizardPage extends JavadocWizardPage { protected Button fAntBrowseButton; private Button fCheckbrowser; protected Text fAntText; protected Button fOverViewButton; private Button fOverViewBrowseButton; protected Button fAntButton; private Composite fLowerComposite; protected Text fOverViewText; protected Text fExtraOptionsText; private StatusInfo fOverviewStatus; private StatusInfo fAntStatus; private JavadocOptionsManager fStore; private JavadocWizard fWizard; private final int OVERVIEWSTATUS= 1; private final int ANTSTATUS= 2; /** * Constructor for JavadocWizardPage. * @param pageName */ protected JavadocSpecificsWizardPage(String pageName, JavadocOptionsManager store) { super(pageName); setDescription(JavadocExportMessages.getString("JavadocSpecificsWizardPage.description")); //$NON-NLS-1$ fStore= store; fOverviewStatus= new StatusInfo(); fAntStatus= new StatusInfo(); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { fWizard= (JavadocWizard) this.getWizard(); fLowerComposite= new Composite(parent, SWT.NONE); fLowerComposite.setLayoutData(createGridData(GridData.FILL_BOTH, 1, 0)); GridLayout layout= createGridLayout(3); layout.marginHeight= 0; fLowerComposite.setLayout(layout); createExtraOptionsGroup(fLowerComposite); createAntGroup(fLowerComposite); setControl(fLowerComposite); WorkbenchHelp.setHelp(fLowerComposite, IJavaHelpContextIds.JAVADOC_SPECIFICS_PAGE); } //end method createControl private void createExtraOptionsGroup(Composite composite) { Composite c= new Composite(composite, SWT.NONE); c.setLayout(createGridLayout(3)); c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 3, 0)); ((GridLayout) c.getLayout()).marginWidth= 0; fOverViewButton= createButton(c, SWT.CHECK, JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewbutton.label"), createGridData(1)); //$NON-NLS-1$ fOverViewText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //there really aught to be a way to specify this ((GridData) fOverViewText.getLayoutData()).widthHint= 200; fOverViewBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewbrowse.label"), createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0)); //$NON-NLS-1$ SWTUtil.setButtonDimensionHint(fOverViewBrowseButton); String str= fStore.getOverview(); if (str.equals("")) { //$NON-NLS-1$ //default fOverViewText.setEnabled(false); fOverViewBrowseButton.setEnabled(false); } else { fOverViewButton.setSelection(true); fOverViewText.setText(str); } createLabel(composite, SWT.NONE, JavadocExportMessages.getString("JavadocSpecificsWizardPage.extraoptionsfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 3, 0)); //$NON-NLS-1$ fExtraOptionsText= createText(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL, 3, 0)); //fExtraOptionsText.setSize(convertWidthInCharsToPixels(60), convertHeightInCharsToPixels(10)); str= fStore.getAdditionalParams(); fExtraOptionsText.setText(str); //Listeners fOverViewButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fOverViewBrowseButton, fOverViewText }) { public void validate() { doValidation(OVERVIEWSTATUS); } }); fOverViewText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(OVERVIEWSTATUS); } }); fOverViewBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleFileBrowseButtonPressed(fOverViewText, new String[] { "*.html" }, JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewbrowsedialog.title")); //$NON-NLS-1$ //$NON-NLS-2$ } }); } private void createAntGroup(Composite composite) { Composite c= new Composite(composite, SWT.NONE); c.setLayout(createGridLayout(3)); c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 3, 0)); ((GridLayout) c.getLayout()).marginWidth= 0; fAntButton= createButton(c, SWT.CHECK, JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbutton.label"), createGridData(3)); //$NON-NLS-1$ createLabel(c, SWT.NONE, JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscripttext.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, 0)); //$NON-NLS-1$ fAntText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //there really aught to be a way to specify this ((GridData) fAntText.getLayoutData()).widthHint= 200; //if multiple projects selected anpath is empty or location of ant file if (fWizard.getSelectedProjects().size() == 1) { fAntText.setText(fStore.getSpecificAntpath((IJavaProject) fWizard.getSelectedProjects().iterator().next())); } else fAntText.setText(fStore.getGeneralAntpath()); fAntBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbrowse.label"), createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0)); //$NON-NLS-1$ SWTUtil.setButtonDimensionHint(fAntBrowseButton); //set enabled fAntButton.setEnabled(fWizard.getSelectedProjects().size() != 1); fAntText.setEnabled(fAntButton.getEnabled()); fAntBrowseButton.setEnabled(fAntButton.getEnabled()); fCheckbrowser= createButton(c, SWT.CHECK, JavadocExportMessages.getString("JavadocSpecificsWizardPage.openbrowserbutton.label"), createGridData(3)); //$NON-NLS-1$ fCheckbrowser.setSelection(fStore.doOpenInBrowser()); fAntButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fAntText, fAntBrowseButton }) { public void validate() { doValidation(ANTSTATUS); } }); fAntText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(ANTSTATUS); } }); fAntBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String temp= fAntText.getText(); IPath path= new Path(temp); String file= path.lastSegment(); if (file == null) file= "javadoc.xml";//$NON-NLS-1$ path= path.removeLastSegments(1); temp= handleFolderBrowseButtonPressed(path.toOSString(), fAntText.getShell(), JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbrowsedialog.title"), JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbrowsedialog.label")); //$NON-NLS-1$ //$NON-NLS-2$ path= new Path(temp); path= path.addTrailingSeparator().append(file); fAntText.setText(path.toOSString()); } }); } //end method createExtraOptionsGroup private void doValidation(int VALIDATE) { File file= null; String ext= null; Path path= null; switch (VALIDATE) { case OVERVIEWSTATUS : fOverviewStatus= new StatusInfo(); if (fOverViewButton.getSelection()) { path= new Path(fOverViewText.getText()); file= path.toFile(); ext= path.getFileExtension(); if ((file == null) || !file.exists()) { fOverviewStatus.setError(JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewnotfound.error")); //$NON-NLS-1$ } else if ((ext == null) || !ext.equalsIgnoreCase("html")) { //$NON-NLS-1$ fOverviewStatus.setError(JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewincorrect.error")); //$NON-NLS-1$ } } break; case ANTSTATUS : fAntStatus= new StatusInfo(); if (fAntButton.getSelection()) { path= new Path(fAntText.getText()); ext= path.getFileExtension(); IPath antSeg= path.removeLastSegments(1); if ((!antSeg.isValidPath(antSeg.toOSString())) || (ext == null) || !(ext.equalsIgnoreCase("xml"))) //$NON-NLS-1$ fAntStatus.setError(JavadocExportMessages.getString("JavadocSpecificsWizardPage.antfileincorrect.error")); //$NON-NLS-1$ else if (path.toFile().exists()) fAntStatus.setWarning(JavadocExportMessages.getString("JavadocSpecificsWizardPage.antfileoverwrite.warning")); //$NON-NLS-1$ } break; } updateStatus(findMostSevereStatus()); } /* * @see JavadocWizardPage#onFinish() */ protected void finish() { String str= fExtraOptionsText.getText(); if (str.length() > 0) fStore.setAdditionalParams(str); else fStore.setAdditionalParams(""); //$NON-NLS-1$ if (fOverViewText.getEnabled()) fStore.setOverview(fOverViewText.getText()); else fStore.setOverview(""); //$NON-NLS-1$ //for now if there are multiple then the ant file is not stored for specific projects if (fAntText.getEnabled()) { fStore.setGeneralAntpath(fAntText.getText()); if (fWizard.getSelectedProjects().size() == 1) fStore.setSpecificAntpath((IJavaProject) fWizard.getSelectedProjects().iterator().next(), fAntText.getText()); } fStore.setOpenInBrowser(fCheckbrowser.getSelection()); } public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { //ant button only enabled if a single project selected fAntButton.setEnabled(fWizard.getSelectedProjects().size() == 1); doValidation(OVERVIEWSTATUS); doValidation(ANTSTATUS); } } public void init() { updateStatus(new StatusInfo()); } private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fAntStatus, fOverviewStatus }); } public boolean generateAnt() { return fAntButton.getSelection(); } }
20,666
Bug 20666 Export JavaDoc should examine jdk compliance
The Export Javadoc wizard should examine the jdk1.3/jdk1.4 compliance for a project and add the appropriate javadoc switch by default to the javadoc args viewer. Result of not fixing: Javadoc users will get errors in the console complaining about all their assert statements, and then have to figure out the switches to add to correct this problem.
resolved fixed
2c506ba
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-20T19:23:18Z
2002-06-19T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocStandardWizardPage.java