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
unknown
report_datetime
unknown
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
5,765
Bug 5765 New Class button in empty workspace should be more supportive
User feedback: "Confused how to create my first project" We should be more supportive in the UI for this special case since it is a first time experience with the UI. Therefore when the workbench is empty we should offer to create a new Java project. Minimal solution is to show an info dialog that explains that user should create a project first and offer a button to open the Java project wizard. The same is true for the new package and new interface buttons.
resolved fixed
ed4c009
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T14:08:51Z"
"2001-11-10T19:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewPackageCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaConventions; 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.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; 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.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewPackageCreationWizardPage extends ContainerPage { private static final String PAGE_NAME= "NewPackageCreationWizardPage"; //$NON-NLS-1$ protected static final String PACKAGE= "NewPackageCreationWizardPage.package"; //$NON-NLS-1$ private StringDialogField fPackageDialogField; /** * Status of last validation of the package field */ protected IStatus fPackageStatus; private IPackageFragment fCreatedPackageFragment; public NewPackageCreationWizardPage(IWorkspaceRoot root) { super(PAGE_NAME, root); setTitle(NewWizardMessages.getString("NewPackageCreationWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewPackageCreationWizardPage.description")); //$NON-NLS-1$ fCreatedPackageFragment= null; PackageFieldAdapter adapter= new PackageFieldAdapter(); fPackageDialogField= new StringDialogField(); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewPackageCreationWizardPage.package.label")); //$NON-NLS-1$ fPackageStatus= new StatusInfo(); } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= null; if (selection != null && !selection.isEmpty()) { Object selectedElement= selection.getFirstElement(); if (selectedElement instanceof IAdaptable) { IAdaptable adaptable= (IAdaptable) selectedElement; jelem= (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (jelem == null) { IResource resource= (IResource) adaptable.getAdapter(IResource.class); if (resource != null) { IProject proj= resource.getProject(); if (proj != null) { jelem= JavaCore.create(proj); } } } } } if (jelem == null) { jelem= EditorUtility.getActiveEditorJavaInput(); } initContainerPage(jelem); setPackageText(""); //$NON-NLS-1$ updateStatus(findMostSevereStatus()); } // -------- UI Creation --------- /** * @see WizardPage#createControl */ public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int nColumns= 3; MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.minimumHeight= SWTUtil.convertHeightInCharsToPixels(20, composite); layout.numColumns= 3; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); fPackageDialogField.setFocus(); setControl(composite); WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.NEW_PACKAGE_WIZARD_PAGE)); } protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); } // -------- PackageFieldAdapter -------- private class PackageFieldAdapter implements IDialogFieldListener { // --------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { fPackageStatus= packageChanged(); // tell all others handleFieldChanged(PACKAGE); } } // -------- update message ---------------- /** * Called when a dialog field on this page changed * @see ContainerPage#fieldUpdated */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); } // do status line update updateStatus(findMostSevereStatus()); } /** * Finds the most severe error (if there is one) */ protected IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fContainerStatus, fPackageStatus); } // ----------- validation ---------- /** * Verify the input for the package field */ private IStatus packageChanged() { StatusInfo status= new StatusInfo(); String packName= fPackageDialogField.getText(); if (!"".equals(packName)) { //$NON-NLS-1$ IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewPackageCreationWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewPackageCreationWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ } } else { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.DefaultPackageExists")); //$NON-NLS-1$ return status; } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getUnderlyingResource().getFullPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.IsOutputFolder")); //$NON-NLS-1$ return status; } } if (pack.exists()) { if (pack.containsJavaResources() || !pack.hasSubpackages()) { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.PackageExists")); //$NON-NLS-1$ } else { status.setWarning(NewWizardMessages.getString("NewPackageCreationWizardPage.warning.PackageNotShown")); //$NON-NLS-1$ } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } return status; } protected String getPackageText() { return fPackageDialogField.getText(); } protected void setPackageText(String str) { fPackageDialogField.setText(str); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { createPackage(monitor); } catch (JavaModelException e) { throw new InvocationTargetException(e); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } public IPackageFragment getNewPackageFragment() { return fCreatedPackageFragment; } protected void createPackage(IProgressMonitor monitor) throws JavaModelException, CoreException, InterruptedException { IPackageFragmentRoot root= getPackageFragmentRoot(); String packName= getPackageText(); fCreatedPackageFragment= root.createPackageFragment(packName, true, monitor); } }
5,765
Bug 5765 New Class button in empty workspace should be more supportive
User feedback: "Confused how to create my first project" We should be more supportive in the UI for this special case since it is a first time experience with the UI. Therefore when the workbench is empty we should offer to create a new Java project. Minimal solution is to show an info dialog that explains that user should create a project first and offer a button to open the Java project wizard. The same is true for the new package and new interface buttons.
resolved fixed
ed4c009
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T14:08:51Z"
"2001-11-10T19:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/OpenClassWizardAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jdt.internal.ui.actions.AbstractOpenWizardAction; public class OpenClassWizardAction extends AbstractOpenWizardAction { public OpenClassWizardAction() { } public OpenClassWizardAction(String label, Class[] acceptedTypes) { super(label, acceptedTypes, false); } protected Wizard createWizard() { return new NewClassCreationWizard(); } protected boolean shouldAcceptElement(Object obj) { return NewGroup.isOnBuildPath(obj) && !NewGroup.isInArchive(obj); } }
5,765
Bug 5765 New Class button in empty workspace should be more supportive
User feedback: "Confused how to create my first project" We should be more supportive in the UI for this special case since it is a first time experience with the UI. Therefore when the workbench is empty we should offer to create a new Java project. Minimal solution is to show an info dialog that explains that user should create a project first and offer a button to open the Java project wizard. The same is true for the new package and new interface buttons.
resolved fixed
ed4c009
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T14:08:51Z"
"2001-11-10T19:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/OpenInterfaceWizardAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jdt.internal.ui.actions.AbstractOpenWizardAction; public class OpenInterfaceWizardAction extends AbstractOpenWizardAction { public OpenInterfaceWizardAction() { } public OpenInterfaceWizardAction(String label, Class[] acceptedTypes) { super(label, acceptedTypes, false); } protected Wizard createWizard() { return new NewInterfaceCreationWizard(); } protected boolean shouldAcceptElement(Object obj) { return NewGroup.isOnBuildPath(obj) && !NewGroup.isInArchive(obj); } }
5,765
Bug 5765 New Class button in empty workspace should be more supportive
User feedback: "Confused how to create my first project" We should be more supportive in the UI for this special case since it is a first time experience with the UI. Therefore when the workbench is empty we should offer to create a new Java project. Minimal solution is to show an info dialog that explains that user should create a project first and offer a button to open the Java project wizard. The same is true for the new package and new interface buttons.
resolved fixed
ed4c009
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T14:08:51Z"
"2001-11-10T19:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/OpenPackageWizardAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jdt.internal.ui.actions.AbstractOpenWizardAction; public class OpenPackageWizardAction extends AbstractOpenWizardAction { public OpenPackageWizardAction() { } public OpenPackageWizardAction(String label, Class[] acceptedTypes) { super(label, acceptedTypes, false); } protected Wizard createWizard() { return new NewPackageCreationWizard(); } protected boolean shouldAcceptElement(Object obj) { return NewGroup.isOnBuildPath(obj) && !NewGroup.isInArchive(obj); } }
5,765
Bug 5765 New Class button in empty workspace should be more supportive
User feedback: "Confused how to create my first project" We should be more supportive in the UI for this special case since it is a first time experience with the UI. Therefore when the workbench is empty we should offer to create a new Java project. Minimal solution is to show an info dialog that explains that user should create a project first and offer a button to open the Java project wizard. The same is true for the new package and new interface buttons.
resolved fixed
ed4c009
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T14:08:51Z"
"2001-11-10T19:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/OpenProjectWizardAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jdt.internal.ui.actions.AbstractOpenWizardAction; public class OpenProjectWizardAction extends AbstractOpenWizardAction { public OpenProjectWizardAction() { } public OpenProjectWizardAction(String label, Class[] acceptedTypes) { super(label, acceptedTypes, true); } protected Wizard createWizard() { return new NewProjectCreationWizard(); } }
5,765
Bug 5765 New Class button in empty workspace should be more supportive
User feedback: "Confused how to create my first project" We should be more supportive in the UI for this special case since it is a first time experience with the UI. Therefore when the workbench is empty we should offer to create a new Java project. Minimal solution is to show an info dialog that explains that user should create a project first and offer a button to open the Java project wizard. The same is true for the new package and new interface buttons.
resolved fixed
ed4c009
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T14:08:51Z"
"2001-11-10T19:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/OpenSnippetWizardAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jdt.internal.ui.actions.AbstractOpenWizardAction; public class OpenSnippetWizardAction extends AbstractOpenWizardAction { public OpenSnippetWizardAction() { } public OpenSnippetWizardAction(String label, Class[] acceptedTypes) { super(label, acceptedTypes, false); } protected Wizard createWizard() { return new NewSnippetFileCreationWizard(); } protected boolean shouldAcceptElement(Object obj) { return !NewGroup.isInArchive(obj); } }
6,009
Bug 6009 New class wizard doesn't get context right for nested classes
Build 20011106. - with a .java file open in the editor, - click the new class button - check "Enclosing Type" - the field is blank - it should default to the current type in the editor
verified fixed
eaf4bd8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T15:51:14Z"
"2001-11-16T17:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/JavaModelUtil.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.util; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IOpenable; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; 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.core.Signature; /** * Utility methods for the Java Model. */ public class JavaModelUtil { /** * Finds a type by its qualified type name (dot separated). * @param jproject The java project to search in * @param str The fully qualified name (type name with enclosing type names and package (all separated by dots)) * @return The type found, or null if not existing * The method does not find inner types. Waiting for a Java Core solution */ public static IType findType(IJavaProject jproject, String fullyQualifiedName) throws JavaModelException { String pathStr= fullyQualifiedName.replace('.', '/') + ".java"; //$NON-NLS-1$ IJavaElement jelement= jproject.findElement(new Path(pathStr)); if (jelement == null) { // try to find it as inner type String qualifier= Signature.getQualifier(fullyQualifiedName); if (qualifier.length() > 0) { IType type= findType(jproject, qualifier); // recursive! if (type != null) { IType res= type.getType(Signature.getSimpleName(fullyQualifiedName)); if (res.exists()) { return res; } } } } else if (jelement.getElementType() == IJavaElement.COMPILATION_UNIT) { String simpleName= Signature.getSimpleName(fullyQualifiedName); return ((ICompilationUnit) jelement).getType(simpleName); } else if (jelement.getElementType() == IJavaElement.CLASS_FILE) { return ((IClassFile) jelement).getType(); } return null; } /** * Finds a type by package and type name. * @param jproject the java project to search in * @param pack The package name * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots)) * @return the type found, or null if not existing */ public static IType findType(IJavaProject jproject, String pack, String typeQualifiedName) throws JavaModelException { // should be supplied from java core int dot= typeQualifiedName.indexOf('.'); if (dot == -1) { return findType(jproject, concatenateName(pack, typeQualifiedName)); } IPath packPath; if (pack.length() > 0) { packPath= new Path(pack.replace('.', '/')); } else { packPath= new Path(""); //$NON-NLS-1$ } // fixed for 1GEXEI6: ITPJUI:ALL - Incorrect error message on class creation wizard IPath path= packPath.append(typeQualifiedName.substring(0, dot) + ".java"); //$NON-NLS-1$ IJavaElement elem= jproject.findElement(path); if (elem instanceof ICompilationUnit) { return findTypeInCompilationUnit((ICompilationUnit)elem, typeQualifiedName); } else if (elem instanceof IClassFile) { path= packPath.append(typeQualifiedName.replace('.', '$') + ".class"); //$NON-NLS-1$ elem= jproject.findElement(path); if (elem instanceof IClassFile) { return ((IClassFile)elem).getType(); } } return null; } /** * Finds a type container by container name. * The returned element will be of type <code>IType</code> or a <code>IPackageFragment</code>. * <code>null</code> is returned if the type container could not be found. * @param jproject The Java project defining the context to search * @param typeContainerName A dot separarted name of the type container * @see #getTypeContainerName() */ public static IJavaElement findTypeContainer(IJavaProject jproject, String typeContainerName) throws JavaModelException { // try to find it as type IJavaElement result= findType(jproject, typeContainerName); if (result == null) { // find it as package IPath path= new Path(typeContainerName.replace('.', '/')); result= jproject.findElement(path); if (!(result instanceof IPackageFragment)) { result= null; } } return result; } /** * Finds a type in a compilation unit. Typical usage is to find the corresponding * type in a working copy. * @param cu the compilation unit to search in * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots)) * @return the type found, or null if not existing */ public static IType findTypeInCompilationUnit(ICompilationUnit cu, String typeQualifiedName) throws JavaModelException { IType[] types= cu.getAllTypes(); for (int i= 0; i < types.length; i++) { String currName= getTypeQualifiedName(types[i]); if (typeQualifiedName.equals(currName)) { return types[i]; } } return null; } /** * Finds a a member in a compilation unit. Typical usage is to find the corresponding * member in a working copy. * @param cu the compilation unit (eg. working copy) to search in * @param member the member (eg. from the original) * @return the member found, or null if not existing */ public static IMember findMemberInCompilationUnit(ICompilationUnit cu, IMember member) throws JavaModelException { if (member.getElementType() == IJavaElement.TYPE) { return findTypeInCompilationUnit(cu, getTypeQualifiedName((IType)member)); } else { IType declaringType= findTypeInCompilationUnit(cu, getTypeQualifiedName(member.getDeclaringType())); if (declaringType != null) { IMember result= null; switch (member.getElementType()) { case IJavaElement.FIELD: result= declaringType.getField(member.getElementName()); break; case IJavaElement.METHOD: IMethod meth= (IMethod) member; result= findMethod(meth.getElementName(), meth.getParameterTypes(), meth.isConstructor(), declaringType); break; case IJavaElement.INITIALIZER: result= declaringType.getInitializer(1); break; } if (result != null && result.exists()) { return result; } } } return null; } /** * Returns the element contained in the given set with the same name * as the given key. * * @param set the set to choose from * @param key the key to look for * @return the member of the given set with the same name as the given key */ private static IJavaElement find(IJavaElement[] set, IJavaElement key) { if (set == null) return null; String name= key.getElementName(); if (name == null) return null; for (int i= 0; i < set.length; i++) { if (name.equals(set[i].getElementName())) return set[i]; } return null; } /** * Returns the element of the given compilation unit which is "equal" to the * given element. Note that the given element usually has a parent different * from the given compilation unit. * * @param cu the cu to search in * @param element the element to look for * @return an element of the given cu "equal" to the given element */ public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) throws JavaModelException { if (element instanceof IMember) return findMemberInCompilationUnit(cu, (IMember) element); int type= element.getElementType(); switch (type) { case IJavaElement.IMPORT_CONTAINER: return cu.getImportContainer(); case IJavaElement.PACKAGE_DECLARATION: return find(cu.getPackageDeclarations(), element); case IJavaElement.IMPORT_DECLARATION: return find(cu.getImports(), element); case IJavaElement.COMPILATION_UNIT: return cu; } return null; } /** * Returns the qualified type name of the given type using '.' as separators. * This is a replace for IType.getTypeQualifiedName() * which uses '$' as separators. As '$' is also a valid character in an id * this is ambiguous. JavaCore PR: 1GCFUNT */ public static String getTypeQualifiedName(IType type) { StringBuffer buf= new StringBuffer(); getTypeQualifiedName(type, buf); return buf.toString(); } private static void getTypeQualifiedName(IType type, StringBuffer buf) { IType outerType= type.getDeclaringType(); if (outerType != null) { getTypeQualifiedName(outerType, buf); buf.append('.'); } buf.append(type.getElementName()); } /** * Returns the fully qualified name of the given type using '.' as separators. * This is a replace for IType.getFullyQualifiedTypeName * which uses '$' as separators. As '$' is also a valid character in an id * this is ambiguous. JavaCore PR: 1GCFUNT */ public static String getFullyQualifiedName(IType type) { StringBuffer buf= new StringBuffer(); String packName= type.getPackageFragment().getElementName(); if (packName.length() > 0) { buf.append(packName); buf.append('.'); } getTypeQualifiedName(type, buf); return buf.toString(); } /** * Returns the fully qualified name of a type's container. (package name or enclosing type name) */ public static String getTypeContainerName(IType type) { IType outerType= type.getDeclaringType(); if (outerType != null) { return getFullyQualifiedName(outerType); } else { return type.getPackageFragment().getElementName(); } } /** * Returns the raw class path entry corresponding to a package fragment root * or null if there isn't a corresponding entry. */ public static IClasspathEntry getRawClasspathEntry(IPackageFragmentRoot root) throws JavaModelException { IPath path= root.getPath(); IClasspathEntry[] entries= root.getJavaProject().getRawClasspath(); for (int i= 0; i < entries.length; i++) { IClasspathEntry curr= entries[i]; if (curr.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { curr= JavaCore.getResolvedClasspathEntry(curr); } if (curr != null && curr.getContentKind() == root.getKind() && path.equals(curr.getPath())) { return entries[i]; } } return null; } /** * Concatenates two names. Uses a dot for separation. * Both strings can be empty or <code>null</code>. */ public static String concatenateName(String name1, String name2) { StringBuffer buf= new StringBuffer(); if (name1 != null && name1.length() > 0) { buf.append(name1); if (name2 != null && name2.length() > 0) { buf.append('.'); buf.append(name2); } } return buf.toString(); } /** * Evaluates if a member (possible from another package) is visible from * elements in a package. * @param member The member to test the visibility for * @param pack The package in focus */ public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException { int otherflags= member.getFlags(); if (Flags.isPublic(otherflags) || Flags.isProtected(otherflags)) { return true; } else if (Flags.isPrivate(otherflags)) { return false; } IPackageFragment otherpack= (IPackageFragment) findParentOfKind(member, IJavaElement.PACKAGE_FRAGMENT); return (pack != null && pack.equals(otherpack)); } /** * Returns true if the element is on the build path of the given project */ public static boolean isOnBuildPath(IJavaProject jproject, IJavaElement element) throws JavaModelException { IPath rootPath; if (element.getElementType() == IJavaElement.JAVA_PROJECT) { rootPath= ((IJavaProject)element).getProject().getFullPath(); } else { IPackageFragmentRoot root= getPackageFragmentRoot(element); if (root == null) { return false; } rootPath= root.getPath(); } return jproject.findPackageFragmentRoot(rootPath) != null; } /** * Returns the package fragment root of <code>IJavaElement</code>. If the given * element is already a package fragment root, the element itself is returned. */ public static IPackageFragmentRoot getPackageFragmentRoot(IJavaElement element) { return (IPackageFragmentRoot)findElementOfKind(element, IJavaElement.PACKAGE_FRAGMENT_ROOT); } /** * Returns the first openable parent. If the given element is openable, the element * itself is returned. */ public static IOpenable getOpenable(IJavaElement element) { while (element != null && !(element instanceof IOpenable)) { element= element.getParent(); } return (IOpenable) element; } /** * Returns the parent of the supplied java element that conforms to the given * parent type or <code>null</code>, if such a parent doesn't exit. */ public static IJavaElement findParentOfKind(IJavaElement element, int kind) { if (element == null) return null; return findElementOfKind(element.getParent(), kind); } /** * Returns the first java element that conforms to the given type walking the * java element's parent relationship. If the given element alrady conforms to * the given kind, the element is returned. * Returns <code>null</code> if no such element exits. */ public static IJavaElement findElementOfKind(IJavaElement element, int kind) { while (element != null && element.getElementType() != kind) element= element.getParent(); return element; } /** * Finds a method in a type. * This searches for a method with the same name and signature. Parameter types are only * compared by the simple name, no resolving for the fully qualified type name is done. * Constructors are only compared by parameters, not the name. * @param name The name of the method to find * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> * @param isConstructor If the method is a constructor * @return The first found method or <code>null</code>, if nothing found */ public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaModelException { return findMethod(name, paramTypes, isConstructor, type.getMethods()); } /** * Finds a method by name. * This searches for a method with a name and signature. Parameter types are only * compared by the simple name, no resolving for the fully qualified type name is done. * Constructors are only compared by parameters, not the name. * @param name The name of the method to find * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> * @param isConstructor If the method is a constructor * @param methods The methods to search in * @return The found method or <code>null</code>, if nothing found */ public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IMethod[] methods) throws JavaModelException { for (int i= methods.length - 1; i >= 0; i--) { if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i])) { return methods[i]; } } return null; } /** * Finds a method declararion in a type's hierarchy. The search is top down, so this * returns the first declaration of the method in the hierarchy. * This searches for a method with a name and signature. Parameter types are only * compared by the simple name, no resolving for the fully qualified type name is done. * Constructors are only compared by parameters, not the name. * @param name The name of the method to find * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> * @param isConstructor If the method is a constructor * @return The first method found or null, if nothing found */ public static IMethod findMethodDeclarationInHierarchy(ITypeHierarchy hierarchy, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { IType[] superTypes= hierarchy.getAllSupertypes(hierarchy.getType()); for (int i= superTypes.length - 1; i >= 0; i--) { IMethod found= findMethod(name, paramTypes, isConstructor, superTypes[i]); if (found != null) { return found; } } return null; } /** * Finds a method implementation in a type's hierarchy. The search is bottom-up, so this * returns the overwritten method. * This searches for a method with a name and signature. Parameter types are only * compared by the simple name, no resolving for the fully qualified type name is done. * Constructors are only compared by parameters, not the name. * @param name The name of the method to find * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> * @param isConstructor If the method is a constructor * @return The first method found or null, if nothing found */ public static IMethod findMethodImplementationInHierarchy(ITypeHierarchy hierarchy, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { IType[] superTypes= hierarchy.getAllSupertypes(hierarchy.getType()); for (int i= 0; i < superTypes.length; i++) { IMethod found= findMethod(name, paramTypes, isConstructor, superTypes[i]); if (found != null) { return found; } } return null; } /** * Tests if a method equals to the given signature. * Parameter types are only compared by the simple name, no resolving for * the fully qualified type name is done. Constructors are only compared by * parameters, not the name. * @param Name of the method * @param The type signatures of the parameters e.g. <code>{"QString;","I"}</code> * @param Specifies if the method is a constructor * @return Returns <code>true</code> if the method has the given name and parameter types and constructor state. */ public static boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod curr) throws JavaModelException { if (isConstructor || name.equals(curr.getElementName())) { if (isConstructor == curr.isConstructor()) { String[] currParamTypes= curr.getParameterTypes(); if (paramTypes.length == currParamTypes.length) { for (int i= 0; i < paramTypes.length; i++) { String t1= Signature.getSimpleName(Signature.toString(paramTypes[i])); String t2= Signature.getSimpleName(Signature.toString(currParamTypes[i])); if (!t1.equals(t2)) { return false; } } return true; } } } return false; } /** * Checks whether the given type has a valid main method or not. */ public static boolean hasMainMethod(IType type) throws JavaModelException { String[] paramSignature= { Signature.createArraySignature(Signature.createTypeSignature("String", false), 1) }; IMethod method= findMethod("main", paramSignature, false, type); if (method != null) { int flags= method.getFlags(); return Flags.isStatic(flags) && Flags.isPublic(flags) && Signature.SIG_VOID.equals(method.getReturnType()); } return false; } /** * Tests if a method is a main method. Does not resolve the parameter types. * Method must exist. */ public static boolean isMainMethod(IMethod method) throws JavaModelException { if ("main".equals(method.getElementName()) && Signature.SIG_VOID.equals(method.getReturnType())) { //$NON-NLS-1$ int flags= method.getFlags(); if (Flags.isStatic(flags) && Flags.isPublic(flags)) { String[] paramTypes= method.getParameterTypes(); if (paramTypes.length == 1) { String name= Signature.toString(paramTypes[0]); return "String[]".equals(Signature.getSimpleName(name)); //$NON-NLS-1$ } } } return false; } /** * Resolves a type name in the context of the declaring type. * @param refTypeSig the type name in signature notation (for example 'QVector') * this can also be an array type, but dimensions will be ignored. * @param declaringType the context for resolving (type where the reference was made in) * @return returns the fully qualified type name or build-in-type name. * if a unresoved type couldn't be resolved null is returned */ public static String getResolvedTypeName(String refTypeSig, IType declaringType) throws JavaModelException { int arrayCount= Signature.getArrayCount(refTypeSig); char type= refTypeSig.charAt(arrayCount); if (type == Signature.C_UNRESOLVED) { int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1); if (semi == -1) { throw new IllegalArgumentException(); } String name= refTypeSig.substring(arrayCount + 1, semi); String[][] resolvedNames= declaringType.resolveType(name); if (resolvedNames != null && resolvedNames.length > 0) { return JavaModelUtil.concatenateName(resolvedNames[0][0], resolvedNames[0][1]); } return null; } else { return Signature.toString(refTypeSig.substring(arrayCount)); } } }
6,009
Bug 6009 New class wizard doesn't get context right for nested classes
Build 20011106. - with a .java file open in the editor, - click the new class button - check "Enclosing Type" - the field is blank - it should default to the current type in the editor
verified fixed
eaf4bd8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-20T15:51:14Z"
"2001-11-16T17:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/TypePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.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.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.compiler.env.IConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.StubUtility; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; /** * <code>TypePage</code> contains controls and validation routines for a 'New Type WizardPage' * Implementors decide which components to add and to enable. Implementors can also * customize the validation code. * <code>TypePage</code> is intended to serve as base class of all wizards that create types. * Applets, Servlets, Classes, Interfaces... * See <code>NewClassCreationWizardPage</code> or <code>NewInterfaceCreationWizardPage</code> for an * example usage of TypePage. */ public abstract class TypePage extends ContainerPage { private final static String PAGE_NAME= "TypePage"; //$NON-NLS-1$ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPlugin.getDefault().getImageRegistry().get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; public TypePage(boolean isClass, String pageName, IWorkspaceRoot root) { super(pageName, root); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("TypePage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("TypePage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("TypePage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("TypePage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("TypePage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("TypePage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("TypePage.interfaces.class.label") : NewWizardMessages.getString("TypePage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("TypePage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("TypePage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("TypePage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("TypePage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("TypePage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the type page with a given * Java element as selection. * @param elem The initial selection of this page or null if no * selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; if (elem != null) { pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT); try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(null, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { initializeDialogUnits(composite); (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, 4); } /** * Creates the controls for the enclosing type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { fEnclosingTypeSelection.doFillIntoGrid(composite, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); c.setLayoutData(new MGridData(MGridData.FILL_HORIZONTAL)); LayoutUtil.setHorizontalSpan(c, 2); c= fEnclosingTypeDialogField.getChangeControl(composite); c.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); } /** * Creates the controls for the type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); } /** * Creates the controls for the modifiers radio/ceckbox buttons. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); LayoutUtil.setHorizontalSpan(fAccMdfButtons.getSelectionButtonsGroup(composite), nColumns - 2); fAccMdfButtons.setButtonsMinWidth(70); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); LayoutUtil.setHorizontalSpan(fOtherMdfButtons.getSelectionButtonsGroup(composite), nColumns - 2); fOtherMdfButtons.setButtonsMinWidth(70); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { initializeDialogUnits(composite); fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); MGridData gd= (MGridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; } /** * Sets the focus on the container if empty, elso on type name. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /** * Called whenever a content of a field has changed. * Implementors of TypePage can hook in. * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Gets the text of package field. */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Gets the text of enclosing type field. */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * @return Returns <code>null</code> if the input could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the package fragment can be changed by the user */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the encloding type corresponding to the current input. * @return Returns <code>null</code> if enclosing type is not selected or the input could not * be resolved. */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the enclosing type can be changed by the user */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns <code>true</code> if the enclosing type selection check box is enabled. */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type selection checkbox. * @param canBeModified Selects if the enclosing type selection can be changed by the user */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Gets the type name. */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Gets the selected modifiers. * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= IConstants.AccPublic; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= IConstants.AccPrivate; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= IConstants.AccProtected; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= IConstants.AccAbstract; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= IConstants.AccFinal; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= IConstants.AccStatic; } return mdf; } /** * Sets the modifiers. * @param canBeModified Selects if the modifiers can be changed by the user * @see IConstants */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Gets the content of the super class text field. */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * @param canBeModified Selects if the super class can be changed by the user */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Gets the currently chosen super interfaces. * @return returns a list of String */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * @param interfacesNames a list of String */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * Called when the package field has changed. * The method validates the package name and returns the status of the validation * This also updates the package fragment model. * Can be extended to add more validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getUnderlyingResource().getFullPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("TypePage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass } fCurrPackage= pack; } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= fPackageDialogField.getText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Called when the enclosing type name has changed. * The method validates the enclosing type and returns the status of the validation * This also updates the enclosing type model. * Can be extended to add more validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= JavaModelUtil.findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); return status; } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("TypePage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Called when the superclass name has changed. * The method validates the superclass name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (!val.isOK()) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("TypePage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, sclassName); } } return type; } /** * Called when the list of super interface has changed. * The method validates the superinterfaces and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= JavaModelUtil.findType(root.getJavaProject(), intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass, checking is an extra } } } return status; } /** * Called when the modifiers have changed. * The method validates the modifiers and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("TypePage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null) { packages= froot.getChildren(); } } catch (JavaModelException e) { } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("TypePage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); if (fCurrPackage != null) { dialog.setInitialSelections(new Object[] { fCurrPackage }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_TYPES); dialog.setTitle(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ if (fCurrEnclosingType != null) { dialog.setInitialSelections(new Object[] { fCurrEnclosingType }); dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1)); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES); dialog.setTitle(NewWizardMessages.getString("TypePage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.SuperClassDialog.message")); //$NON-NLS-1$ if (fSuperClass != null) { dialog.setFilter(fSuperClass.getElementName()); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(NewWizardMessages.getString("TypePage.InterfacesDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("TypePage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= fTypeNameDialogField.getText(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); lineDelimiter= StubUtility.getLineDelimiterUsed(parentCU); String content= createTypeBody(imports, lineDelimiter); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); String content= createTypeBody(imports, lineDelimiter); createdType= enclosingType.createType(content, null, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so the type can be parsed correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1)); if (methods.length > 0) { for (int i= 0; i < methods.length; i++) { createdType.createMethod(methods[i], null, false, null); } // add imports imports.create(!isInnerClass, null); } monitor.worked(1); String formattedContent= StubUtility.codeFormat(createdType.getSource(), indent, lineDelimiter); ISourceRange range= createdType.getSourceRange(); IBuffer buf= createdType.getCompilationUnit().getBuffer(); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. Only valid after createType has been invoked */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, IImportsStructure imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ buf.append(Signature.getSimpleName(typename)); if (fSuperClass != null) { imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass)); } else { imports.addImport(typename); } } } private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); imports.addImport(typename); buf.append(Signature.getSimpleName(typename)); if (i < last) { buf.append(", "); //$NON-NLS-1$ } } } } /* * Called from createType to construct the source for this type */ private String createTypeBody(IImportsStructure imports, String lineDelimiter) { StringBuffer buf= new StringBuffer(); int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append(" {"); //$NON-NLS-1$ buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * Called from createType to allow adding methods for the newly created type * Returns array of sources of the methods that have to be added * @param parent The type where the methods will be added to */ protected String[] evalMethods(IType parent, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return new String[0]; } /** * Creates the bodies of all unimplemented methods or/and all constructors * Can be used by implementors of TypePage to add method stub checkboxes */ protected String[] constructInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { StubUtility.evalConstructors(type, superclass, newMethods, imports); } } if (doUnimplementedMethods) { StubUtility.evalUnimplementedMethods(type, hierarchy, false, newMethods, imports); } return (String[]) newMethods.toArray(new String[newMethods.size()]); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
4,071
Bug 4071 Format option loses place in editor (1GHQFU6)
If you select the Format option from the pop up menu in a Java Editor your current selection location is lost requiring you to search around for it again. STEPS 1) Open a relatively large .java file 2) Go near the bottom 3) Select format - you are sent back to the top. NOTES:
resolved fixed
4531f76
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-21T10:05:49Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaFormattingStrategy.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.formatter.IFormattingStrategy; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.corext.refactoring.TextUtilities; import org.eclipse.jdt.internal.formatter.CodeFormatter; import org.eclipse.jdt.internal.ui.codemanipulation.StubUtility; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; public class JavaFormattingStrategy implements IFormattingStrategy { private String fInitialIndentation; private ISourceViewer fViewer; public JavaFormattingStrategy(ISourceViewer viewer) { fViewer = viewer; } /** * @see IFormattingStrategy#formatterStarts(String) */ public void formatterStarts(String initialIndentation) { fInitialIndentation= initialIndentation; } /** * @see IFormattingStrategy#formatterStops() */ public void formatterStops() { } /** * @see IFormattingStrategy#format(String, boolean, String, int[]) */ public String format(String content, boolean isLineStart, String indentation, int[] positions) { CodeFormatter formatter= new CodeFormatter(JavaCore.getOptions()); IDocument doc= fViewer.getDocument(); String lineDelimiter= StubUtility.getLineDelimiterFor(doc); formatter.options.setLineSeparator(lineDelimiter); formatter.setPositionsToMap(positions); int indent= 0; if (fInitialIndentation != null) { indent= TextUtilities.getIndent(fInitialIndentation, CodeFormatterPreferencePage.getTabSize()); } formatter.setInitialIndentationLevel(indent); return formatter.formatSourceString(content); } }
6,147
Bug 6147 Templates don't work in "Show source of selected element only" mode
null
resolved fixed
762a35c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-21T11:13:20Z"
"2001-11-21T10:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionUI.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.text.link; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>. */ public class LinkedPositionUI implements LinkedPositionListener, ITextInputListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener { /** * A listener for notification when the user cancelled the edit operation. */ public interface ExitListener { void exit(boolean accept); } // leave flags private static final int UNINSTALL= 1; // uninstall linked position manager private static final int COMMIT= 2; // commit changes private static final int DOCUMENT_CHANGED= 4; // document has changed private static final int UPDATE_CARET= 8; // update caret private static final String CARET_POSITION= "LinkedPositionUI.caret.position"; private static final IPositionUpdater fgUpdater= new DefaultPositionUpdater(CARET_POSITION); private final ITextViewer fViewer; private final LinkedPositionManager fManager; private final Color fFrameColor; private int fFinalCaretOffset= -1; // no final caret offset private Position fFramePosition; private int fCaretOffset; private ExitListener fExitListener; /** * Creates a user interface for <code>LinkedPositionManager</code>. * * @param viewer the text viewer. * @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>. */ public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) { Assert.isNotNull(viewer); Assert.isNotNull(manager); fViewer= viewer; fManager= manager; fManager.setLinkedPositionListener(this); fFrameColor= viewer.getTextWidget().getDisplay().getSystemColor(SWT.COLOR_RED); } /** * Sets the final position of the caret when the linked mode is exited * successfully by leaving the last linked position using TAB. */ public void setFinalCaretOffset(int offset) { fFinalCaretOffset= offset; } /** * Sets a <code>CancelListener</code> which is notified if the linked mode * is exited unsuccessfully by hitting ESC. */ public void setCancelListener(ExitListener listener) { fExitListener= listener; } /* * @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int) */ public void setCurrentPosition(Position position, int caretOffset) { if (!fFramePosition.equals(position)) { redrawRegion(); fFramePosition= position; } fCaretOffset= caretOffset; } /** * Enters the linked mode. The linked mode can be left by calling * <code>exit</code>. * * @see exit(boolean) */ public void enter() { // track final caret IDocument document= fViewer.getDocument(); document.addPositionCategory(CARET_POSITION); document.addPositionUpdater(fgUpdater); try { if (fFinalCaretOffset != -1) document.addPosition(CARET_POSITION, new Position(fFinalCaretOffset)); } catch (BadLocationException e) { openErrorDialog(fViewer.getTextWidget().getShell(), e); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } fViewer.addTextInputListener(this); StyledText text= fViewer.getTextWidget(); text.addVerifyListener(this); text.addVerifyKeyListener(this); text.addModifyListener(this); text.addPaintListener(this); text.showSelection(); fFramePosition= fManager.getFirstPosition(); if (fFramePosition == null) leave(UNINSTALL | COMMIT | UPDATE_CARET); } /** * @see LinkedPositionManager.LinkedPositionListener#exit(boolean) */ public void exit(boolean success) { // no UNINSTALL since manager has already uninstalled itself leave((success ? COMMIT : 0) | UPDATE_CARET); } /** * Returns the cursor selection, after having entered the linked mode. * <code>enter()</code> must be called prior to a call to this method. */ public IRegion getSelectedRegion() { if (fFramePosition == null) return new Region(fFinalCaretOffset, 0); else return new Region(fFramePosition.getOffset(), fFramePosition.getLength()); } private void leave(int flags) { if ((flags & UNINSTALL) != 0) fManager.uninstall((flags & COMMIT) != 0); StyledText text= fViewer.getTextWidget(); text.removePaintListener(this); text.removeModifyListener(this); text.removeVerifyKeyListener(this); text.removeVerifyListener(this); fViewer.removeTextInputListener(this); try { IRegion region= fViewer.getVisibleRegion(); IDocument document= fViewer.getDocument(); if (((flags & COMMIT) != 0) && ((flags & DOCUMENT_CHANGED) == 0) && ((flags & UPDATE_CARET) != 0)) { Position[] positions= document.getPositions(CARET_POSITION); if ((positions != null) && (positions.length != 0)) { int offset= positions[0].getOffset() - region.getOffset(); if ((offset >= 0) && (offset <= region.getLength())) text.setSelection(offset, offset); } } document.removePositionUpdater(fgUpdater); document.removePositionCategory(CARET_POSITION); if (fExitListener != null) fExitListener.exit( ((flags & COMMIT) != 0) || ((flags & DOCUMENT_CHANGED) != 0)); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } if ((flags & DOCUMENT_CHANGED) == 0) text.redraw(); } private void next() { redrawRegion(); fFramePosition= fManager.getNextPosition(fFramePosition.getOffset()); if (fFramePosition == null) { leave(UNINSTALL | COMMIT | UPDATE_CARET); } else { selectRegion(); redrawRegion(); } } private void previous() { redrawRegion(); Position position= fManager.getPreviousPosition(fFramePosition.getOffset()); if (position == null) { fViewer.getTextWidget().getDisplay().beep(); } else { fFramePosition= position; selectRegion(); redrawRegion(); } } /* * @see VerifyKeyListener#verifyKey(VerifyEvent) */ public void verifyKey(VerifyEvent event) { switch (event.character) { // [SHIFT-]TAB = hop between edit boxes case 0x09: { Point selection= fViewer.getTextWidget().getSelection(); IRegion region= fViewer.getVisibleRegion(); int offset= selection.x + region.getOffset(); int length= selection.y - selection.x; // if tab was treated as a document change, would it exceed variable range? if (!LinkedPositionManager.includes(fFramePosition, offset, length)) { leave(UNINSTALL | COMMIT | UPDATE_CARET); return; } } if (event.stateMask == SWT.SHIFT) previous(); else next(); event.doit= false; break; // ESC = cancel case 0x1B: leave(UNINSTALL); event.doit= false; break; } } /* * @see VerifyListener#verifyText(VerifyEvent) */ public void verifyText(VerifyEvent event) { if (!event.doit) return; int offset= event.start; int length= event.end - event.start; // allow changes only within linked positions when coming through UI if (!fManager.anyPositionIncludes(offset, length)) leave(UNINSTALL | COMMIT); } /* * @see PaintListener#paintControl(PaintEvent) */ public void paintControl(PaintEvent event) { if (fFramePosition == null) return; IRegion region= fViewer.getVisibleRegion(); int offset= fFramePosition.getOffset() - region.getOffset(); int length= fFramePosition.getLength(); StyledText text= fViewer.getTextWidget(); // support for bidi Point minLocation= getMinimumLocation(text, offset, length); Point maxLocation= getMaximumLocation(text, offset, length); int x1= minLocation.x; int x2= minLocation.x + maxLocation.x - minLocation.x - 1; int y= minLocation.y + text.getLineHeight() - 1; GC gc= event.gc; gc.setForeground(fFrameColor); gc.drawLine(x1, y, x2, y); } private static Point getMinimumLocation(StyledText text, int offset, int length) { Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x < minLocation.x) minLocation.x= location.x; if (location.y < minLocation.y) minLocation.y= location.y; } return minLocation; } private static Point getMaximumLocation(StyledText text, int offset, int length) { Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x > maxLocation.x) maxLocation.x= location.x; if (location.y > maxLocation.y) maxLocation.y= location.y; } return maxLocation; } private void redrawRegion() { IRegion region= fViewer.getVisibleRegion(); int offset= fFramePosition.getOffset() - region.getOffset(); int length= fFramePosition.getLength(); fViewer.getTextWidget().redrawRange(offset, length, true); } private void selectRegion() { IRegion region= fViewer.getVisibleRegion(); int start= fFramePosition.getOffset() - region.getOffset(); int end= fFramePosition.getLength() + start; fViewer.getTextWidget().setSelection(start, end); } private void updateCaret() { IRegion region= fViewer.getVisibleRegion(); int offset= fFramePosition.getOffset() + fCaretOffset - region.getOffset(); if ((offset >= 0) && (offset <= region.getLength())) fViewer.getTextWidget().setCaretOffset(offset); } /* * @see ModifyListener#modifyText(ModifyEvent) */ public void modifyText(ModifyEvent e) { // reposition caret after StyledText redrawRegion(); updateCaret(); } private static void openErrorDialog(Shell shell, Exception e) { MessageDialog.openError(shell, LinkedPositionMessages.getString("LinkedPositionUI.error.title"), e.getMessage()); //$NON-NLS-1$ } /* * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { // 5326: leave linked mode on document change int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED); leave(flags); } /* * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { } }
4,172
Bug 4172 feature: auto select "Inherited Abstract Methods" (1GJLAE7)
jkca (9/5/2001 11:56:30 AM) It would be nice if the New Class Wizard automatically selected "Inherited Abstract Methods" when the user adds an interface to the Extended Interfaces list. I argue that most users will want this selected if they plan to implement an interface.
verified fixed
b03d332
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-21T17:04:26Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewClassCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; 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.SubProgressMonitor; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewClassCreationWizardPage extends TypePage { private final static String PAGE_NAME= "NewClassCreationWizardPage"; //$NON-NLS-1$ private SelectionButtonDialogFieldGroup fMethodStubsButtons; public NewClassCreationWizardPage(IWorkspaceRoot root) { super(true, PAGE_NAME, root); setTitle(NewWizardMessages.getString("NewClassCreationWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewClassCreationWizardPage.description")); //$NON-NLS-1$ String[] buttonNames3= new String[] { NewWizardMessages.getString("NewClassCreationWizardPage.methods.main"), NewWizardMessages.getString("NewClassCreationWizardPage.methods.constructors"), //$NON-NLS-1$ //$NON-NLS-2$ NewWizardMessages.getString("NewClassCreationWizardPage.methods.inherited") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames3, 1); fMethodStubsButtons.setLabelText(NewWizardMessages.getString("NewClassCreationWizardPage.methods.label")); //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); updateStatus(findMostSevereStatus()); } // ------ validation -------- /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fContainerStatus, isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus, fTypeNameStatus, fModifierStatus, fSuperClassStatus, fSuperInterfacesStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); updateStatus(findMostSevereStatus()); } // ------ ui -------- /* * @see WizardPage#createControl */ public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createEnclosingTypeControls(composite, nColumns); createSeparator(composite, nColumns); createTypeNameControls(composite, nColumns); createModifierControls(composite, nColumns); // createSeparator(composite, nColumns); createSuperClassControls(composite, nColumns); createSuperInterfacesControls(composite, nColumns); //createSeparator(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setControl(composite); setFocus(); WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.NEW_CLASS_WIZARD_PAGE)); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); DialogField.createEmptySpace(composite); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } // ---- creation ---------------- /* * @see TypePage#evalMethods */ protected String[] evalMethods(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); boolean doConstr= fMethodStubsButtons.isSelected(1); boolean doInherited= fMethodStubsButtons.isSelected(2); String[] meth= constructInheritedMethods(type, doConstr, doInherited, imports, new SubProgressMonitor(monitor, 1)); for (int i= 0; i < meth.length; i++) { newMethods.add(meth[i]); } if (monitor != null) { monitor.done(); } if (fMethodStubsButtons.isSelected(0)) { String main= "public static void main(String[] args) {}"; //$NON-NLS-1$ newMethods.add(main); } return (String[]) newMethods.toArray(new String[newMethods.size()]); } }
3,793
Bug 3793 Wrong formating when creating inner class using wizard (1GEUE91)
- select TestCase - create a new class using TestCase as an eclosing type observe: - new type is added at the end. Quasi standard is having the new type at the beginning. - new type doesn't have indention. NOTES: GDA (6/5/01 11:08:09 AM) defer
verified fixed
a29ff25
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-21T17:12:16Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/TypePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.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.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.compiler.env.IConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.StubUtility; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; /** * <code>TypePage</code> contains controls and validation routines for a 'New Type WizardPage' * Implementors decide which components to add and to enable. Implementors can also * customize the validation code. * <code>TypePage</code> is intended to serve as base class of all wizards that create types. * Applets, Servlets, Classes, Interfaces... * See <code>NewClassCreationWizardPage</code> or <code>NewInterfaceCreationWizardPage</code> for an * example usage of TypePage. */ public abstract class TypePage extends ContainerPage { private final static String PAGE_NAME= "TypePage"; //$NON-NLS-1$ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPlugin.getDefault().getImageRegistry().get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; public TypePage(boolean isClass, String pageName, IWorkspaceRoot root) { super(pageName, root); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("TypePage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("TypePage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("TypePage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("TypePage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("TypePage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("TypePage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("TypePage.interfaces.class.label") : NewWizardMessages.getString("TypePage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("TypePage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("TypePage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("TypePage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("TypePage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("TypePage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the type page with a given * Java element as selection. * @param elem The initial selection of this page or null if no * selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= JavaModelUtil.findPrimaryType(cu); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { initializeDialogUnits(composite); (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, 4); } /** * Creates the controls for the enclosing type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { fEnclosingTypeSelection.doFillIntoGrid(composite, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); c.setLayoutData(new MGridData(MGridData.FILL_HORIZONTAL)); LayoutUtil.setHorizontalSpan(c, 2); c= fEnclosingTypeDialogField.getChangeControl(composite); c.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); } /** * Creates the controls for the type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); } /** * Creates the controls for the modifiers radio/ceckbox buttons. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); LayoutUtil.setHorizontalSpan(fAccMdfButtons.getSelectionButtonsGroup(composite), nColumns - 2); fAccMdfButtons.setButtonsMinWidth(70); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); LayoutUtil.setHorizontalSpan(fOtherMdfButtons.getSelectionButtonsGroup(composite), nColumns - 2); fOtherMdfButtons.setButtonsMinWidth(70); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { initializeDialogUnits(composite); fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); MGridData gd= (MGridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; } /** * Sets the focus on the container if empty, elso on type name. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /** * Called whenever a content of a field has changed. * Implementors of TypePage can hook in. * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Gets the text of package field. */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Gets the text of enclosing type field. */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * @return Returns <code>null</code> if the input could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the package fragment can be changed by the user */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the encloding type corresponding to the current input. * @return Returns <code>null</code> if enclosing type is not selected or the input could not * be resolved. */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the enclosing type can be changed by the user */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns <code>true</code> if the enclosing type selection check box is enabled. */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type selection checkbox. * @param canBeModified Selects if the enclosing type selection can be changed by the user */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Gets the type name. */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Gets the selected modifiers. * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= IConstants.AccPublic; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= IConstants.AccPrivate; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= IConstants.AccProtected; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= IConstants.AccAbstract; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= IConstants.AccFinal; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= IConstants.AccStatic; } return mdf; } /** * Sets the modifiers. * @param canBeModified Selects if the modifiers can be changed by the user * @see IConstants */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Gets the content of the super class text field. */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * @param canBeModified Selects if the super class can be changed by the user */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Gets the currently chosen super interfaces. * @return returns a list of String */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * @param interfacesNames a list of String */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * Called when the package field has changed. * The method validates the package name and returns the status of the validation * This also updates the package fragment model. * Can be extended to add more validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getUnderlyingResource().getFullPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("TypePage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass } fCurrPackage= pack; } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= fPackageDialogField.getText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Called when the enclosing type name has changed. * The method validates the enclosing type and returns the status of the validation * This also updates the enclosing type model. * Can be extended to add more validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= JavaModelUtil.findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); return status; } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("TypePage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Called when the superclass name has changed. * The method validates the superclass name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (!val.isOK()) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("TypePage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, sclassName); } } return type; } /** * Called when the list of super interface has changed. * The method validates the superinterfaces and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= JavaModelUtil.findType(root.getJavaProject(), intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass, checking is an extra } } } return status; } /** * Called when the modifiers have changed. * The method validates the modifiers and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("TypePage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null) { packages= froot.getChildren(); } } catch (JavaModelException e) { } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("TypePage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); if (fCurrPackage != null) { dialog.setInitialSelections(new Object[] { fCurrPackage }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_TYPES); dialog.setTitle(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ if (fCurrEnclosingType != null) { dialog.setInitialSelections(new Object[] { fCurrEnclosingType }); dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1)); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES); dialog.setTitle(NewWizardMessages.getString("TypePage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.SuperClassDialog.message")); //$NON-NLS-1$ if (fSuperClass != null) { dialog.setFilter(fSuperClass.getElementName()); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(NewWizardMessages.getString("TypePage.InterfacesDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("TypePage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= fTypeNameDialogField.getText(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); lineDelimiter= StubUtility.getLineDelimiterUsed(parentCU); String content= createTypeBody(imports, lineDelimiter); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); String content= createTypeBody(imports, lineDelimiter); createdType= enclosingType.createType(content, null, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so the type can be parsed correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1)); if (methods.length > 0) { for (int i= 0; i < methods.length; i++) { createdType.createMethod(methods[i], null, false, null); } // add imports imports.create(!isInnerClass, null); } monitor.worked(1); String formattedContent= StubUtility.codeFormat(createdType.getSource(), indent, lineDelimiter); ISourceRange range= createdType.getSourceRange(); IBuffer buf= createdType.getCompilationUnit().getBuffer(); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. Only valid after createType has been invoked */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, IImportsStructure imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ buf.append(Signature.getSimpleName(typename)); if (fSuperClass != null) { imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass)); } else { imports.addImport(typename); } } } private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); imports.addImport(typename); buf.append(Signature.getSimpleName(typename)); if (i < last) { buf.append(", "); //$NON-NLS-1$ } } } } /* * Called from createType to construct the source for this type */ private String createTypeBody(IImportsStructure imports, String lineDelimiter) { StringBuffer buf= new StringBuffer(); int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append(" {"); //$NON-NLS-1$ buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * Called from createType to allow adding methods for the newly created type * Returns array of sources of the methods that have to be added * @param parent The type where the methods will be added to */ protected String[] evalMethods(IType parent, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return new String[0]; } /** * Creates the bodies of all unimplemented methods or/and all constructors * Can be used by implementors of TypePage to add method stub checkboxes */ protected String[] constructInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { StubUtility.evalConstructors(type, superclass, newMethods, imports); } } if (doUnimplementedMethods) { StubUtility.evalUnimplementedMethods(type, hierarchy, false, newMethods, imports); } return (String[]) newMethods.toArray(new String[newMethods.size()]); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
4,077
Bug 4077 JDK1.4 - Assertions - text coloring should deal with 'assert' (1GHS3A3)
If the JavaCore option related to source mode is set in 1.4 mode, then 'assert' is a keyword which has to be coloured properly. Assertions are only supported in the 2.0 stream of jdtcore. Configurable options are also subject to improvements. NOTES:
verified fixed
2a5b45c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-21T17:40:14Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Hashtable; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.DialogPageContextComputer; 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.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; /* * The page for setting the compiler options. */ public class CompilerPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { // Preference store keys, see JavaCore.getOptions private static final String PREF_LOCAL_VARIABLE_ATTR= "org.eclipse.jdt.core.compiler.debug.localVariable"; private static final String PREF_LINE_NUMBER_ATTR= "org.eclipse.jdt.core.compiler.debug.lineNumber"; private static final String PREF_SOURCE_FILE_ATTR= "org.eclipse.jdt.core.compiler.debug.sourceFile"; private static final String PREF_CODEGEN_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.codegen.unusedLocal"; private static final String PREF_CODEGEN_TARGET_PLATFORM= "org.eclipse.jdt.core.compiler.codegen.targetPlatform"; private static final String PREF_PB_UNREACHABLE_CODE= "org.eclipse.jdt.core.compiler.problem.unreachableCode"; private static final String PREF_PB_INVALID_IMPORT= "org.eclipse.jdt.core.compiler.problem.invalidImport"; private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= "org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod"; private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= "org.eclipse.jdt.core.compiler.problem.methodWithConstructorName"; private static final String PREF_PB_DEPRECATION= "org.eclipse.jdt.core.compiler.problem.deprecation"; private static final String PREF_PB_HIDDEN_CATCH_BLOCK= "org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock"; private static final String PREF_PB_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.problem.unusedLocal"; private static final String PREF_PB_UNUSED_PARAMETER= "org.eclipse.jdt.core.compiler.problem.unusedParameter"; private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= "org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation"; private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= "org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral"; private static final String PREF_PB_ASSERT_AS_IDENTIFIER= "org.eclipse.jdt.core.compiler.problem.assertIdentifier"; private static final String PREF_SOURCE_COMPATIBILITY= "org.eclipse.jdt.core.compiler.source"; // values private static final String GENERATE= "generate"; private static final String DO_NOT_GENERATE= "do not generate"; private static final String PRESERVE= "preserve"; private static final String OPTIMIZE_OUT= "optimize out"; private static final String VERSION_1_1= "1.1"; private static final String VERSION_1_2= "1.2"; private static final String VERSION_1_3= "1.3"; private static final String VERSION_1_4= "1.4"; private static final String ERROR= "error"; private static final String WARNING= "warning"; private static final String IGNORE= "ignore"; private static String[] getAllKeys() { return new String[] { PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL, PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL, PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS, PREF_PB_ASSERT_AS_IDENTIFIER, PREF_SOURCE_COMPATIBILITY }; } /** * Initializes the current options (read from preference store) */ public static void initDefaults(IPreferenceStore store) { Hashtable hashtable= JavaCore.getDefaultOptions(); Hashtable currOptions= JavaCore.getOptions(); String[] allKeys= getAllKeys(); for (int i= 0; i < allKeys.length; i++) { String key= allKeys[i]; String defValue= (String) hashtable.get(key); if (defValue != null) { store.setDefault(key, defValue); } else { JavaPlugin.logErrorMessage("CompilerPreferencePage: value is null: " + key); } // update the JavaCore options from the pref store String val= store.getString(key); if (val != null) { currOptions.put(key, val); } } JavaCore.setOptions(currOptions); } private static class ControlData { private String fKey; private String[] fValues; public ControlData(String key, String[] values) { fKey= key; fValues= values; } public String getKey() { return fKey; } public String getValue(boolean selection) { int index= selection ? 0 : 1; return fValues[index]; } public String getValue(int index) { return fValues[index]; } public int getSelection(String value) { for (int i= 0; i < fValues.length; i++) { if (value.equals(fValues[i])) { return i; } } throw new IllegalArgumentException(); } } private Hashtable fWorkingValues; private ArrayList fCheckBoxes; private ArrayList fComboBoxes; private SelectionListener fSelectionListener; public CompilerPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(JavaUIMessages.getString("CompilerPreferencePage.description")); //$NON-NLS-1$ fWorkingValues= JavaCore.getOptions(); fCheckBoxes= new ArrayList(); fComboBoxes= new ArrayList(); fSelectionListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) {} public void widgetSelected(SelectionEvent e) { controlChanged(e.widget); } }; } /** * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /** * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages super.createControl(parent); WorkbenchHelp.setHelp(getControl(), new DialogPageContextComputer(this, IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE)); } /** * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), JavaUIMessages.getString("CompilerPreferencePage.warning"), JavaUIMessages.getString("CompilerPreferencePage.ignore") }; GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite warningsComposite= new Composite(folder, SWT.NULL); warningsComposite.setLayout(layout); String label= JavaUIMessages.getString("CompilerPreferencePage.pb_unreachable_code.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_invalid_import.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_method_naming.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_hidden_catchblock.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_local.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_parameter.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_synth_access_emul.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_non_externalized_strings.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels); label= JavaUIMessages.getString("CompilerPreferencePage.pb_assert_as_identifier.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels); String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE }; layout= new GridLayout(); layout.numColumns= 2; Composite codeGenComposite= new Composite(folder, SWT.NULL); codeGenComposite.setLayout(layout); label= JavaUIMessages.getString("CompilerPreferencePage.variable_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues); label= JavaUIMessages.getString("CompilerPreferencePage.line_number_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues); label= JavaUIMessages.getString("CompilerPreferencePage.source_file_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues); label= JavaUIMessages.getString("CompilerPreferencePage.codegen_unused_local.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }); String[] values= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 }; String[] valuesLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.jvm11"), JavaUIMessages.getString("CompilerPreferencePage.jvm12"), JavaUIMessages.getString("CompilerPreferencePage.jvm13"), JavaUIMessages.getString("CompilerPreferencePage.jvm14") }; label= JavaUIMessages.getString("CompilerPreferencePage.codegen_targetplatform.label"); //$NON-NLS-1$ addComboBox(codeGenComposite, label, PREF_CODEGEN_TARGET_PLATFORM, values, valuesLabels); values= new String[] { VERSION_1_3, VERSION_1_4 }; valuesLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.version13"), JavaUIMessages.getString("CompilerPreferencePage.version14") }; label= JavaUIMessages.getString("CompilerPreferencePage.source_compatibility.label"); //$NON-NLS-1$ addComboBox(codeGenComposite, label, PREF_SOURCE_COMPATIBILITY, values, valuesLabels); TabItem item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.tabtitle")); //$NON-NLS-1$ item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_WARNING)); item.setControl(warningsComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.generation.tabtitle")); //$NON-NLS-1$ item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE)); item.setControl(codeGenComposite); return folder; } private void addCheckBox(Composite parent, String label, String key, String[] values) { ControlData data= new ControlData(key, values); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan= 2; Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); checkBox.setData(data); checkBox.setLayoutData(gd); checkBox.addSelectionListener(fSelectionListener); String currValue= (String)fWorkingValues.get(key); checkBox.setSelection(data.getSelection(currValue) == 0); fCheckBoxes.add(checkBox); } private void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels) { ControlData data= new ControlData(key, values); Label labelControl= new Label(parent, SWT.NONE); labelControl.setText(label); labelControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData gd= new GridData(); gd.horizontalAlignment= GridData.END; Combo comboBox= new Combo(parent, SWT.READ_ONLY); comboBox.setItems(valueLabels); comboBox.setData(data); comboBox.setLayoutData(gd); comboBox.addSelectionListener(fSelectionListener); String currValue= (String)fWorkingValues.get(key); comboBox.select(data.getSelection(currValue)); fComboBoxes.add(comboBox); } private void controlChanged(Widget widget) { ControlData data= (ControlData) widget.getData(); String newValue= null; if (widget instanceof Button) { newValue= data.getValue(((Button)widget).getSelection()); } else if (widget instanceof Combo) { newValue= data.getValue(((Combo)widget).getSelectionIndex()); } else { return; } fWorkingValues.put(data.getKey(), newValue); } /* * @see IPreferencePage#performOk() */ public boolean performOk() { String[] allKeys= getAllKeys(); // preserve other options // store in JCore and the preferences Hashtable actualOptions= JavaCore.getOptions(); IPreferenceStore store= getPreferenceStore(); boolean hasChanges= false; for (int i= 0; i < allKeys.length; i++) { String key= allKeys[i]; String val= (String) fWorkingValues.get(key); String oldVal= (String) actualOptions.get(key); hasChanges= hasChanges | !val.equals(oldVal); actualOptions.put(key, val); store.putValue(key, val); } JavaCore.setOptions(actualOptions); if (hasChanges) { String title= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.title"); String message= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.message"); if (MessageDialog.openQuestion(getShell(), title, message)) { doFullBuild(); } } return super.performOk(); } private void doFullBuild() { ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); try { dialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (InterruptedException e) { // cancelled by user } catch (InvocationTargetException e) { String title= JavaUIMessages.getString("CompilerPreferencePage.builderror.title"); String message= JavaUIMessages.getString("CompilerPreferencePage.builderror.message"); ExceptionHandler.handle(e, getShell(), title, message); } } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fWorkingValues= JavaCore.getDefaultOptions(); updateControls(); super.performDefaults(); } private void updateControls() { // update the UI for (int i= fCheckBoxes.size() - 1; i >= 0; i--) { Button curr= (Button) fCheckBoxes.get(i); ControlData data= (ControlData) curr.getData(); String currValue= (String) fWorkingValues.get(data.getKey()); curr.setSelection(data.getSelection(currValue) == 0); } for (int i= fComboBoxes.size() - 1; i >= 0; i--) { Combo curr= (Combo) fComboBoxes.get(i); ControlData data= (ControlData) curr.getData(); String currValue= (String) fWorkingValues.get(data.getKey()); curr.select(data.getSelection(currValue)); } } }
4,077
Bug 4077 JDK1.4 - Assertions - text coloring should deal with 'assert' (1GHS3A3)
If the JavaCore option related to source mode is set in 1.4 mode, then 'assert' is a keyword which has to be coloured properly. Assertions are only supported in the 2.0 stream of jdtcore. Configurable options are also subject to improvements. NOTES:
verified fixed
2a5b45c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-21T17:40:14Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCodeScanner.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.ArrayList; import java.util.List; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.rules.EndOfLineRule; import org.eclipse.jface.text.rules.SingleLineRule; import org.eclipse.jface.text.rules.Token; import org.eclipse.jface.text.rules.WhitespaceRule; import org.eclipse.jface.text.rules.WordRule; import org.eclipse.jdt.ui.text.IColorManager; import org.eclipse.jdt.ui.text.IJavaColorConstants; import org.eclipse.jdt.internal.ui.text.AbstractJavaScanner; import org.eclipse.jdt.internal.ui.text.JavaWhitespaceDetector; import org.eclipse.jdt.internal.ui.text.JavaWordDetector; /** * A Java code scanner. */ public final class JavaCodeScanner extends AbstractJavaScanner { private static String[] fgKeywords= { "abstract", //$NON-NLS-1$ "break", //$NON-NLS-1$ "case", "catch", "class", "const", "continue", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "default", "do", //$NON-NLS-2$ //$NON-NLS-1$ "else", "extends", //$NON-NLS-2$ //$NON-NLS-1$ "final", "finally", "for", //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "goto", //$NON-NLS-1$ "if", "implements", "import", "instanceof", "interface", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "native", "new", //$NON-NLS-2$ //$NON-NLS-1$ "package", "private", "protected", "public", //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "return", //$NON-NLS-1$ "static", "super", "switch", "synchronized", //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "this", "throw", "throws", "transient", "try", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "volatile", //$NON-NLS-1$ "while" //$NON-NLS-1$ }; private static String[] fgTypes= { "void", "boolean", "char", "byte", "short", "strictfp", "int", "long", "float", "double" }; //$NON-NLS-1$ //$NON-NLS-5$ //$NON-NLS-7$ //$NON-NLS-6$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-2$ private static String[] fgConstants= { "false", "null", "true" }; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ private String[] fgTokenProperties= { IJavaColorConstants.JAVA_KEYWORD, IJavaColorConstants.JAVA_TYPE, IJavaColorConstants.JAVA_STRING, IJavaColorConstants.JAVA_DEFAULT }; /** * Creates a Java code scanner */ public JavaCodeScanner(IColorManager manager, IPreferenceStore store) { super(manager, store); initialize(); } /* * @see AbstractJavaScanner#getTokenProperties() */ protected String[] getTokenProperties() { return fgTokenProperties; } /* * @see AbstractJavaScanner#createRules() */ protected List createRules() { List rules= new ArrayList(); // Add rule for strings and character constants. Token token= getToken(IJavaColorConstants.JAVA_STRING); rules.add(new SingleLineRule("\"", "\"", token, '\\')); //$NON-NLS-2$ //$NON-NLS-1$ rules.add(new SingleLineRule("'", "'", token, '\\')); //$NON-NLS-2$ //$NON-NLS-1$ // Add generic whitespace rule. rules.add(new WhitespaceRule(new JavaWhitespaceDetector())); // Add word rule for keywords, types, and constants. token= getToken(IJavaColorConstants.JAVA_DEFAULT); WordRule wordRule= new WordRule(new JavaWordDetector(), token); token= getToken(IJavaColorConstants.JAVA_KEYWORD); for (int i=0; i<fgKeywords.length; i++) wordRule.addWord(fgKeywords[i], token); token= getToken(IJavaColorConstants.JAVA_TYPE); for (int i=0; i<fgTypes.length; i++) wordRule.addWord(fgTypes[i], token); for (int i=0; i<fgConstants.length; i++) wordRule.addWord(fgConstants[i], token); rules.add(wordRule); setDefaultReturnToken(getToken(IJavaColorConstants.JAVA_DEFAULT)); return rules; } }
4,155
Bug 4155 Source Attachment wizard for variable classpath entries not correct (1GJ6X9P)
(1) Create a directory containing a .jar file and a .zip source archive for the jar The .zip archive should have a non-null root path to the source. (2) create a classpath variable which points to this directory (3) place this .jar file in your classpath using the variable (4) use the Java Source Attachment wizard to set the source archive Attempt to use the "root variable path". The "browse..." button is inactive unless the text field is non-empty. If the text field is non-empty, pressing the browse... button shows the source archive no matter what is in the field. If you make a selection in the paths shown that are relative to the archive, any path that is deeper than the first is entered without the intervening path variables. For example, suppose the archive resolves to c:\blort\blort.zip. I can type "junk" in the root variable path field to activate the "browse..." button. Pressing "browse..." shows the structure of "c:\blort\blort.zip". If I select work/src/main as the source root directory in blort.zip for blort.jar and press OK the text field for "root variable path" now reads: junk/main. NOTES:
resolved fixed
ffa99aa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-21T17:40:41Z"
"2001-10-11T03:13:20Z"
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.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.zip.ZipFile; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; 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.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.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.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.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.SWTUtil; 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.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; /** * 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 IStatusChangeListener fContext; private StringButtonDialogField fFileNameField; private SelectionButtonDialogField fInternalButtonField; private StringButtonDialogField fPrefixField; private StringButtonDialogField fJavaDocField; private boolean fIsVariableEntry; private IStatus fNameStatus; private IStatus fPrefixStatus; private IStatus fJavaDocStatus; private IPath fJARPath; /** * 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 URL fJavaDocLocation; private IWorkspaceRoot fRoot; private Control fSWTWidget; private CLabel fFullPathResolvedLabel; private CLabel fPrefixResolvedLabel; private IClasspathEntry fOldEntry; public SourceAttachmentBlock(IWorkspaceRoot root, IStatusChangeListener context, IClasspathEntry oldEntry) { fContext= context; fRoot= root; fOldEntry= oldEntry; // fIsVariableEntry specifies if the UI is for a variable entry fIsVariableEntry= (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE); fNameStatus= new StatusInfo(); fPrefixStatus= new StatusInfo(); fJavaDocStatus= new StatusInfo(); fJARPath= (oldEntry != null) ? oldEntry.getPath() : Path.EMPTY; SourceAttachmentAdapter adapter= new SourceAttachmentAdapter(); // create the dialog fields (no widgets yet) if (fIsVariableEntry) { 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$ fPrefixField= new VariablePathDialogField(adapter); fPrefixField.setDialogFieldListener(adapter); fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varlabel")); //$NON-NLS-1$ fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varbutton")); //$NON-NLS-1$ ((VariablePathDialogField)fPrefixField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.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$ fPrefixField= new StringButtonDialogField(adapter); fPrefixField.setDialogFieldListener(adapter); fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.label")); //$NON-NLS-1$ fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.button")); //$NON-NLS-1$ } // not used fJavaDocField= new StringButtonDialogField(adapter); fJavaDocField.setDialogFieldListener(adapter); fJavaDocField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.label")); //$NON-NLS-1$ fJavaDocField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.button")); //$NON-NLS-1$ // set the old settings setDefaults(); } public void setDefaults() { if (fOldEntry != null && fOldEntry.getSourceAttachmentPath() != null) { fFileNameField.setText(fOldEntry.getSourceAttachmentPath().toString()); } else { fFileNameField.setText(""); //$NON-NLS-1$ } if (fOldEntry != null && fOldEntry.getSourceAttachmentRootPath() != null) { fPrefixField.setText(fOldEntry.getSourceAttachmentRootPath().toString()); } else { fPrefixField.setText(""); //$NON-NLS-1$ } } /** * 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 */ public IPath getSourceAttachmentRootPath() { if (getSourceAttachmentPath() == null) { return null; } else { return new Path(fPrefixField.getText()); } } /** * Creates the control */ public Control createControl(Composite parent) { fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.numColumns= 4; composite.setLayout(layout); int widthHint= SWTUtil.convertWidthInCharsToPixels(fIsVariableEntry ? 50 : 60, composite); MGridData gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 4; Label message= new Label(composite, SWT.LEFT); message.setLayoutData(gd); message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fJARPath.lastSegment())); if (fIsVariableEntry) { DialogField.createEmptySpace(composite, 1); gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= widthHint; Label desc= new Label(composite, SWT.LEFT + SWT.WRAP); desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.filename.description")); desc.setLayoutData(gd); DialogField.createEmptySpace(composite, 2); } // archive name field fFileNameField.doFillIntoGrid(composite, 4); gd= (MGridData)fFileNameField.getTextControl(null).getLayoutData(); gd.widthHint= widthHint; if (!fIsVariableEntry) { // 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 MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(composite, 2); } // prefix description DialogField.createEmptySpace(composite, 1); gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= widthHint; Label desc= new Label(composite, SWT.LEFT + SWT.WRAP); desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.description")); desc.setLayoutData(gd); DialogField.createEmptySpace(composite, 2); // root path field fPrefixField.doFillIntoGrid(composite, 4); gd= (MGridData)fPrefixField.getTextControl(null).getLayoutData(); gd.widthHint= widthHint; if (fIsVariableEntry) { // label that shows the resolved path for variable jars DialogField.createEmptySpace(composite, 1); fPrefixResolvedLabel= new CLabel(composite, SWT.LEFT); fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false)); fPrefixResolvedLabel.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(composite, 2); } fFileNameField.postSetFocusOnDialogField(parent.getDisplay()); //DialogField.createEmptySpace(composite, 1); //Label jdocDescription= new Label(composite, SWT.LEFT + SWT.WRAP); //jdocDescription.setText(NewWizardMessages.getString(JAVADOC + ".description")); //DialogField.createEmptySpace(composite, 1); //fJavaDocField.doFillIntoGrid(composite, 3); WorkbenchHelp.setHelp(composite, new Object[] { 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()); } } else if (field == fPrefixField) { IPath prefixPath= choosePrefix(); if (prefixPath != null) { fPrefixField.setText(prefixPath.toString()); } } else if (field == fJavaDocField) { URL jdocURL= chooseJavaDocLocation(); if (jdocURL != null) { fJavaDocField.setText(jdocURL.toExternalForm()); } } } // ---------- IDialogFieldListener -------- private void attachmentDialogFieldChanged(DialogField field) { if (field == fFileNameField) { fNameStatus= updateFileNameStatus(); } else if (field == fInternalButtonField) { IPath jarFilePath= chooseInternalJarFile(fFileNameField.getText()); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } return; } else if (field == fPrefixField) { fPrefixStatus= updatePrefixStatus(); } else if (field == fJavaDocField) { fJavaDocStatus= updateJavaDocLocationStatus(); } doStatusLineUpdate(); } private void doStatusLineUpdate() { fPrefixField.enableButton(canBrowsePrefix()); fFileNameField.enableButton(canBrowseFileName()); // set the resolved path for variable jars if (fFullPathResolvedLabel != null) { fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); } if (fPrefixResolvedLabel != null) { fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false)); } IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus, fPrefixStatus, fJavaDocStatus }); fContext.statusChanged(status); } private boolean canBrowseFileName() { if (!fIsVariableEntry) { 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 boolean canBrowsePrefix() { // can browse when the archive name is poiting to a existing file // and (if variable) the prefix variable name is existing if (fResolvedFile != null) { if (fIsVariableEntry) { // prefix has valid format, is resolvable return fPrefixStatus.isOK(); } return true; } 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 updatePrefixStatus() { StatusInfo status= new StatusInfo(); String prefix= fPrefixField.getText(); if (prefix.length() == 0) { // no source attachment path return status; } else { if (!Path.EMPTY.isValidPath(prefix)) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.notvalid")); //$NON-NLS-1$ return status; } IPath path= new Path(prefix); if (fIsVariableEntry) { IPath resolvedPath= getResolvedPath(path); if (resolvedPath == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.varnotexists")); //$NON-NLS-1$ return status; } if (resolvedPath.getDevice() != null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinvar")); //$NON-NLS-1$ return status; } } else { if (path.getDevice() != null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinpath")); //$NON-NLS-1$ return status; } } } return status; } 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 (fIsVariableEntry) { 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.isFile()) { 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= fRoot.findMember(filePath); if (res != null) { file= res.getLocation().toFile(); } if (!file.isFile()) { String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", filePath.toString()); //$NON-NLS-1$ status.setError(message); return status; } fResolvedFile= file; } } return status; } private IStatus updateJavaDocLocationStatus() { StatusInfo status= new StatusInfo(); fJavaDocLocation= null; String jdocLocation= fJavaDocField.getText(); if (!"".equals(jdocLocation)) { //$NON-NLS-1$ try { URL url= new URL(jdocLocation); if ("file".equals(url.getProtocol())) { //$NON-NLS-1$ File dir= new File(url.getFile()); if (!dir.isDirectory()) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.error.notafolder")); //$NON-NLS-1$ return status; } /*else { File indexFile= new File(dir, "index.html"); File packagesFile= new File(dir, "package-list"); if (!packagesFile.exists() || !indexFile.exists()) { fJavaDocStatusInfo.setWarning(NewWizardMessages.getString(ERR_JDOCLOCATION_IDXNOTFOUND)); // only a warning, go on } }*/ } fJavaDocLocation= url; } catch (MalformedURLException e) { status.setError(NewWizardMessages.getFormattedString("SourceAttachmentBlock.javadoc.error.malformed", e.getLocalizedMessage())); //$NON-NLS-1$ return status; } } 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= fJARPath; } IPath resolvedPath= currPath; if (fIsVariableEntry) { resolvedPath= getResolvedPath(currPath); if (resolvedPath == null) { resolvedPath= Path.EMPTY; } } if (ArchiveFileFilter.isArchivePath(resolvedPath)) { resolvedPath= resolvedPath.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(resolvedPath.toOSString()); String res= dialog.open(); if (res != null) { IPath returnPath= new Path(res).makeAbsolute(); if (fIsVariableEntry) { returnPath= modifyPath(returnPath, currPath.segment(0)); } return returnPath; } return null; } /* * Opens a dialog to choose an internal jar. */ private IPath chooseInternalJarFile(String initSelection) { Class[] acceptedClasses= new Class[] { IFile.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); ViewerFilter filter= new ArchiveFileFilter(null); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSel= fRoot.findMember(new Path(initSelection)); if (initSel == null) { initSel= fRoot.findMember(fJARPath); } ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(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(fRoot); dialog.setInitialSelection(initSel); if (dialog.open() == dialog.OK) { IFile file= (IFile) dialog.getFirstResult(); return file.getFullPath(); } return null; } /* * Opens a dialog to choose path in a zip file. */ private IPath choosePrefix() { if (fResolvedFile != null) { IPath currPath= new Path(fPrefixField.getText()); String initSelection= null; if (fIsVariableEntry) { IPath resolvedPath= getResolvedPath(currPath); if (resolvedPath != null) { initSelection= resolvedPath.toString(); } } else { initSelection= currPath.toString(); } try { ZipFile zipFile= new ZipFile(fResolvedFile); ZipContentProvider contentProvider= new ZipContentProvider(); contentProvider.setInitialInput(zipFile); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), new ZipLabelProvider(), contentProvider); dialog.setAllowMultiple(false); dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.message")); //$NON-NLS-1$ dialog.setInput(zipFile); dialog.setInitialSelection(contentProvider.getSelectedNode(initSelection)); if (dialog.open() == dialog.OK) { Object obj= dialog.getFirstResult(); IPath path= new Path(obj.toString()); if (fIsVariableEntry) { path= modifyPath(path, currPath.segment(0)); } return path; } } catch (IOException e) { String title= NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.error.title"); //$NON-NLS-1$ String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.prefixdialog.error.message", fResolvedFile.getPath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); JavaPlugin.log(e); } } return null; } /* * Opens a dialog to choose a root in the file system. */ private URL chooseJavaDocLocation() { String initPath= ""; //$NON-NLS-1$ if (fJavaDocLocation != null && "file".equals(fJavaDocLocation.getProtocol())) { //$NON-NLS-1$ initPath= (new File(fJavaDocLocation.getFile())).getPath(); } DirectoryDialog dialog= new DirectoryDialog(getShell()); dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.jdocdialog.text")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.jdocdialog.message")); //$NON-NLS-1$ dialog.setFilterPath(initPath); String res= dialog.open(); if (res != null) { try { return (new File(res)).toURL(); } catch (MalformedURLException e) { // should not happen JavaPlugin.log(e); } } 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. */ public IRunnableWithProgress getRunnable(final IJavaProject jproject, final Shell shell) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { IClasspathEntry newEntry; if (fIsVariableEntry) { newEntry= JavaCore.newVariableEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), false); } else { newEntry= JavaCore.newLibraryEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), false); } IClasspathEntry[] entries= modifyClasspath(jproject, newEntry, shell); if (entries != null) { jproject.setRawClasspath(entries, monitor); } } catch (JavaModelException e) { throw new InvocationTargetException(e); } } }; } private IClasspathEntry[] modifyClasspath(IJavaProject jproject, IClasspathEntry newEntry, Shell shell) 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 null; } // add new newEntries.add(newEntry); } return (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]); } 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]; } }
5,475
Bug 5475 F4 causes loss of context when called from a method view
1) Open a class with many methods 2) Make sure "show of source element only" is selected 3) Choose a method 4) Press F4 with no selection The class is open on the hierarchy view and the full source is shown in the editor. The method focus was lost. You have to find and select the method again.
resolved fixed
798e9a2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T10:51:58Z"
"2001-11-02T16:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/SelectionProviderMediator.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; /** * A selection provider for viewparts with more that one viewer. * Tracks the focus of the viewers to provide the correct selection. */ public class SelectionProviderMediator implements ISelectionProvider { private class InternalListener implements ISelectionChangedListener, FocusListener { /* * @see ISelectionChangedListener#selectionChanged */ public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } /* * @see FocusListener#focusGained */ public void focusGained(FocusEvent e) { doFocusChanged(e.widget); } /* * @see FocusListener#focusLost */ public void focusLost(FocusEvent e) { propagateFocusChanged(null); } } private Viewer[] fViewers; private InternalListener fListener; private Viewer fViewerInFocus; private ListenerList fSelectionChangedListeners; /** * @param All viewers that can provide a selection */ public SelectionProviderMediator(Viewer[] viewers) { Assert.isNotNull(viewers); fViewers= viewers; fListener= new InternalListener(); fSelectionChangedListeners= new ListenerList(4); fViewerInFocus= null; for (int i= 0; i < fViewers.length; i++) { Viewer viewer= fViewers[i]; viewer.addSelectionChangedListener(fListener); Control control= viewer.getControl(); control.addFocusListener(fListener); } } private void doFocusChanged(Widget control) { for (int i= 0; i < fViewers.length; i++) { if (fViewers[i].getControl() == control) { propagateFocusChanged(fViewers[i]); return; } } } private void doSelectionChanged(SelectionChangedEvent event) { ISelectionProvider provider= event.getSelectionProvider(); if (provider == fViewerInFocus) { fireSelectionChanged(); } } private void propagateFocusChanged(Viewer viewer) { if (viewer != fViewerInFocus) { // Ok to compare by idendity fViewerInFocus= viewer; fireSelectionChanged(); } } private void fireSelectionChanged() { if (fSelectionChangedListeners != null) { SelectionChangedEvent event= new SelectionChangedEvent(this, getSelection()); Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { ISelectionChangedListener listener= (ISelectionChangedListener) listeners[i]; listener.selectionChanged(event); } } } /* * @see ISelectionProvider#addSelectionChangedListener */ public void addSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.add(listener); } /* * @see ISelectionProvider#removeSelectionChangedListener */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.remove(listener); } /* * @see ISelectionProvider#getSelection */ public ISelection getSelection() { if (fViewerInFocus != null) { return fViewerInFocus.getSelection(); } else { return StructuredSelection.EMPTY; } } /* * @see ISelectionProvider#setSelection */ public void setSelection(ISelection selection) { if (fViewerInFocus != null) { fViewerInFocus.setSelection(selection); } } }
5,475
Bug 5475 F4 causes loss of context when called from a method view
1) Open a class with many methods 2) Make sure "show of source element only" is selected 3) Choose a method 4) Press F4 with no selection The class is open on the hierarchy view and the full source is shown in the editor. The method focus was lost. You have to find and select the method again.
resolved fixed
798e9a2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T10:51:58Z"
"2001-11-02T16:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.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.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.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; 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.util.Assert; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.IInputSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.help.ViewContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.compare.JavaReplaceWithEditionAction; import org.eclipse.jdt.internal.ui.dnd.BasicSelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.BuildGroup; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.MarkerErrorTickProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of inut elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private IProblemChangedListener fHierarchyProblemListener; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private MethodsViewer fMethodsViewer; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private boolean fIsEnableMemberFilter; private SashForm fTypeMethodsSplitter; private PageBook fViewerbook; private PageBook fPagebook; private Label fNoHierarchyShownLabel; private Label fEmptyTypesViewer; private ViewForm fTypeViewerViewForm; private ViewForm fMethodViewerViewForm; private CLabel fMethodViewerPaneLabel; private JavaElementLabelProvider fPaneLabelProvider; private IDialogSettings fDialogSettings; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private int fCurrentOrientation; private EnableMemberFilterAction fEnableMemberFilterAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private IPartListener fPartListener; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fHierarchyProblemListener= null; fIsEnableMemberFilter= false; fInputHistory= new ArrayList(); fAllViewers= null; fViewActions= new ToggleViewAction[] { new ToggleViewAction(this, VIEW_ID_TYPE), new ToggleViewAction(this, VIEW_ID_SUPER), new ToggleViewAction(this, VIEW_ID_SUB) }; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); fHistoryDropDownAction= new HistoryDropDownAction(this); fToggleOrientationActions= new ToggleOrientationAction[] { new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE) }; fEnableMemberFilterAction= new EnableMemberFilterAction(this, false); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS); fPaneLabelProvider.setErrorTickManager(new MarkerErrorTickProvider()); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) {} public void partClosed(IWorkbenchPart part) {} public void partDeactivated(IWorkbenchPart part) {} public void partOpened(IWorkbenchPart part) {} }; } /** * 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); } private void updateHistoryEntries() { for (int i= fInputHistory.size() - 1; i >= 0; i--) { IJavaElement type= (IJavaElement) fInputHistory.get(i); if (!type.exists()) { fInputHistory.remove(i); } } } /** * 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() { 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 */ public void selectMember(IMember member) { ICompilationUnit cu= member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { member= (IMember) cu.getOriginal(member); if (member == null) { return; } } Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { fMethodsViewer.getControl().setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } /** * @deprecated */ public IType getInput() { if (fInputElement instanceof IType) { return (IType) fInputElement; } return null; } /** * Sets the input to a new type * @deprecated */ public void setInput(IType type) { setInputElement(type); } /** * Returns the input element of the type hierarchy. * Can be of type <code>IType</code> or <code>IPackageFragment</code> */ public IJavaElement getInputElement() { return fInputElement; } /** * Sets the input to a new element. */ public void setInputElement(IJavaElement element) { if (element != null) { if (element instanceof IMember) { ICompilationUnit cu= ((IMember) element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { element= cu.getOriginal(element); } if (element.getElementType() == IJavaElement.METHOD || element.getElementType() == IJavaElement.FIELD || element.getElementType() == IJavaElement.INITIALIZER) { element= ((IMember) element).getDeclaringType(); } } } if (element != null && !element.equals(fInputElement)) { addHistoryEntry(element); } updateInput(element); } /** * Changes the input to a new type */ private void updateInput(IJavaElement inputElement) { IJavaElement prevInput= fInputElement; fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { // turn off member filtering enableMemberFilter(false); try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } fPagebook.showPage(fTypeMethodsSplitter); if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } updateSelection(fInputElement); updateToolbarButtons(); updateTitle(); } } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); getSite().getPage().removePartListener(fPartListener); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } if (fMethodsViewer != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fMethodsViewer); } super.dispose(); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); ISelectionChangedListener selectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { typeSelectionChanged(event.getSelection()); } }; KeyListener keyListener= createKeyListener(); HierarchyLabelProvider lprovider= new HierarchyLabelProvider(this, new MarkerErrorTickProvider()); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this); initializeTypesViewer(superTypesViewer, selectionChangedListener, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this); initializeTypesViewer(subTypesViewer, selectionChangedListener, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this); initializeTypesViewer(vajViewer, selectionChangedListener, 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 keyPressed(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F4) { OpenTypeHierarchyUtil.open(getSite().getSelectionProvider().getSelection(), getSite().getWorkbenchWindow()); return; } else if (event.keyCode == SWT.F5) { updateHierarchyViewer(); return; } } viewPartKeyShortcuts(event); } }; } private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, ISelectionChangedListener selectionChangedListener, 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(selectionChangedListener); } private Control createMethodViewerControl(Composite parent) { fMethodsViewer= new MethodsViewer(parent, this); fMethodsViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillMethodsViewerContextMenu(menu); } }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite()); fMethodsViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { methodSelectionChanged(event.getSelection()); } }); Control control= fMethodsViewer.getTable(); control.addKeyListener(createKeyListener()); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fMethodsViewer); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_COPY; DragSource source= new DragSource(fMethodsViewer.getControl(), ops); source.setTransfer(transfers); source.addDragListener(new BasicSelectionTransferDragAdapter(fMethodsViewer)); for (int i= 0; i < fAllViewers.length; i++) { TypeHierarchyViewer curr= fAllViewers[i]; curr.addDropSupport(ops, transfers, new TypeHierarchyTransferDropAdapter(curr)); } } private void viewPartKeyShortcuts(KeyEvent event) { if (event.stateMask == SWT.CTRL) { if (event.character == '1') { setView(VIEW_ID_TYPE); } else if (event.character == '2') { setView(VIEW_ID_SUPER); } else if (event.character == '3') { setView(VIEW_ID_SUB); } } } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); initDragAndDrop(); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ MenuManager menu= new MenuManager(); menu.add(fFocusOnTypeAction); fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel)); fPagebook.showPage(fNoHierarchyShownLabel); int orientation; try { orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION); if (orientation < 0 || orientation > 2) { orientation= VIEW_ORIENTATION_VERTICAL; } } catch (NumberFormatException e) { orientation= VIEW_ORIENTATION_VERTICAL; } // force the update fCurrentOrientation= -1; // will fill the main tool bar setOrientation(orientation); // set the filter menu items IActionBars actionBars= getViewSite().getActionBars(); IMenuManager viewMenu= actionBars.getMenuManager(); for (int i= 0; i < fToggleOrientationActions.length; i++) { viewMenu.add(fToggleOrientationActions[i]); } // 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; ISelectionProvider selProvider= new SelectionProviderMediator(trackedViewers); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); selProvider.addSelectionChangedListener(new StatusBarUpdater(slManager)); getSite().setSelectionProvider(selProvider); getSite().getPage().addPartListener(fPartListener); IJavaElement input= determineInputElement(); if (fMemento != null) { restoreState(fMemento, input); } else if (input != null) { setInputElement(input); } else { setViewerVisibility(false); } // fixed for 1GETAYN: ITPJUI:WIN - F1 help does nothing WorkbenchHelp.setHelp(fPagebook, new ViewContextComputer(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW)); } /** * called from ToggleOrientationAction. * @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL */ public void setOrientation(int orientation) { if (fCurrentOrientation != orientation) { boolean methodViewerNeedsUpdate= false; if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed() && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) { if (orientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(false); enableMemberFilter(false); updateMethodViewer(null); } else { if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(true); methodViewerNeedsUpdate= true; } boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL; fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL); updateMainToolbar(horizontal); } 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(boolean horizontal) { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager tbmanager= actionBars.getToolBarManager(); if (horizontal) { clearMainToolBar(tbmanager); ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP); fillMainToolBar(new ToolBarManager(typeViewerToolBar)); fTypeViewerViewForm.setTopLeft(typeViewerToolBar); } else { fTypeViewerViewForm.setTopLeft(null); fillMainToolBar(tbmanager); } } private void fillMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.add(fHistoryDropDownAction); for (int i= 0; i < fViewActions.length; i++) { tbmanager.add(fViewActions[i]); } tbmanager.update(false); } private void clearMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.update(false); } /** * Creates the context menu for the hierarchy viewers */ private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries viewer.contributeToContextMenu(menu); IStructuredSelection selection= (IStructuredSelection)viewer.getSelection(); if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { addOpenPerspectiveItem(menu, selection); } addOpenWithMenu(menu, selection); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnTypeAction); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnSelectionAction); addRefactoring(menu, viewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, viewer); } /** * Creates the context menu for the method viewer */ private void fillMethodsViewerContextMenu(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries fMethodsViewer.contributeToContextMenu(menu); if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) { menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction); } menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer)); addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection()); addRefactoring(menu, fMethodsViewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, fMethodsViewer); } private void addRefactoring(IMenuManager menu, IInputSelectionProvider viewer){ MenuManager refactoring= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.refactor")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, viewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IJavaElement)) return; IResource resource= null; try { resource= ((IJavaElement)element).getUnderlyingResource(); } catch(JavaModelException e) { // ignore } if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } private void addOpenPerspectiveItem(IMenuManager menu, IStructuredSelection selection) { OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, selection); } /** * Toggles between the empty viewer page and the hierarchy */ private void setViewerVisibility(boolean showHierarchy) { if (showHierarchy) { fViewerbook.showPage(getCurrentViewer().getControl()); } else { fViewerbook.showPage(fEmptyTypesViewer); } } /** * Sets the member filter. <code>null</code> disables member filtering. */ private void setMemberFilter(IMember[] memberFilter) { Assert.isNotNull(fAllViewers); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setMemberFilter(memberFilter); } updateHierarchyViewer(); updateTitle(); } private void updateSelection(IJavaElement elem) { ISelection sel= null; if (elem.getElementType() != IJavaElement.TYPE) { Object obj= getCurrentViewer().containsElements(); if (obj != null) { sel= new StructuredSelection(obj); } else { sel= StructuredSelection.EMPTY; } } else { sel= new StructuredSelection(elem); } getCurrentViewer().setSelection(sel); } /** * When the input changed or the hierarchy pane becomes visible, * <code>updateHierarchyViewer<code> brings up the correct view and refreshes * the current tree */ private void updateHierarchyViewer() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); } }; BusyIndicator.showWhile(getDisplay(), runnable); if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) { setViewerVisibility(true); } } else { fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$ setViewerVisibility(false); } } } private void updateMethodViewer(IType input) { if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } fMethodsViewer.setInput(input); } } private void 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); } if (nSelected == 1) { revealElementInEditor(selected.get(0)); } } } 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)); } } else { fSelectedType= null; updateMethodViewer(null); } } } private void revealElementInEditor(Object elem) { // 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; } IEditorPart editorPart= EditorUtility.isOpenInEditor(elem); if (editorPart != null && (elem instanceof IJavaElement)) { try { getSite().getPage().removePartListener(fPartListener); EditorUtility.openInEditor(elem, false); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } catch (CoreException e) { JavaPlugin.log(e); } } } private Display getDisplay() { if (fPagebook != null && !fPagebook.isDisposed()) { return fPagebook.getDisplay(); } return null; } private boolean isChildVisible(Composite pb, Control child) { Control[] children= pb.getChildren(); for (int i= 0; i < children.length; i++) { if (children[i] == child && children[i].isVisible()) return true; } return false; } private void updateTitle() { String viewerTitle= getCurrentViewer().getTitle(); String tooltip; String title; if (fInputElement != null) { String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) }; title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$ tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$ } else { title= viewerTitle; tooltip= viewerTitle; } setTitle(title); setTitleToolTip(tooltip); } private void updateToolbarButtons() { boolean isType= fInputElement instanceof IType; for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; if (action.getViewerIndex() == VIEW_ID_TYPE) { action.setEnabled(fInputElement != null); } else { action.setEnabled(isType); } } } /** * Sets the current view (see view id) * called from ToggleViewAction. Must be called after creation of the viewpart. */ public void setView(int viewerIndex) { Assert.isNotNull(fAllViewers); if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) { fCurrentViewerIndex= viewerIndex; updateHierarchyViewer(); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { updateSelection(fInputElement); } if (!fIsEnableMemberFilter) { typeSelectionChanged(getCurrentViewer().getSelection()); } } updateTitle(); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } fHierarchyProblemListener= getCurrentViewer(); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fHierarchyProblemListener); fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex); getCurrentViewer().getTree().setFocus(); } for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; action.setChecked(fCurrentViewerIndex == action.getViewerIndex()); } } /** * Gets the curret active view index. */ public int getViewIndex() { return fCurrentViewerIndex; } private TypeHierarchyViewer getCurrentViewer() { return fAllViewers[fCurrentViewerIndex]; } /** * called from EnableMemberFilterAction. * Must be called after creation of the viewpart. */ public void enableMemberFilter(boolean on) { if (on != fIsEnableMemberFilter) { fIsEnableMemberFilter= on; if (!on) { Object methodViewerInput= fMethodsViewer.getInput(); setMemberFilter(null); if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) { // avoid that the method view changes content by selecting the previous input getCurrentViewer().setSelection(new StructuredSelection(methodViewerInput)); } else if (fSelectedType != null) { // choose a input that exists getCurrentViewer().setSelection(new StructuredSelection(fSelectedType)); updateMethodViewer(fSelectedType); } } else { methodSelectionChanged(fMethodsViewer.getSelection()); } } fEnableMemberFilterAction.setChecked(on); } /** * Called from ITypeHierarchyLifeCycleListener. * Can be called from any thread */ private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { doTypeHierarchyChangedOnViewers(changedTypes); } }); } } private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (changedTypes == null) { // hierarchy change if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } updateHierarchyViewer(); } } else { // elements in hierarchy modified if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { return (IJavaElement) input; } return null; } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { memento.putString(TAG_INPUT, fInputElement.getHandleIdentifier()); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fMethodsViewer.saveState(memento); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (!input.exists()) { input= null; } } setInputElement(input); Integer viewerIndex= memento.getInteger(TAG_VIEW); if (viewerIndex != null) { setView(viewerIndex.intValue()); } Integer orientation= memento.getInteger(TAG_ORIENTATION); if (orientation != null) { setOrientation(orientation.intValue()); } Integer ratio= memento.getInteger(TAG_RATIO); if (ratio != null) { fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() }); } ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } String selectionId= memento.getString(TAG_SELECTION); if (selectionId != null) { IJavaElement elem= JavaCore.create(selectionId); if (getCurrentViewer().isElementShown(elem)) { getCurrentViewer().setSelection(new StructuredSelection(elem)); } } fMethodsViewer.restoreState(memento); } /** * Link selection to active editor. */ private void editorActivated(IEditorPart editor) { if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) { return; } if (fInputElement == null) { // no type hierarchy shown return; } IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class); try { TypeHierarchyViewer currentViewer= getCurrentViewer(); if (elem instanceof IClassFile) { IType type= ((IClassFile)elem).getType(); if (currentViewer.isElementShown(type)) { currentViewer.setSelection(new StructuredSelection(type)); } } else if (elem instanceof ICompilationUnit) { IType[] allTypes= ((ICompilationUnit)elem).getAllTypes(); for (int i= 0; i < allTypes.length; i++) { if (currentViewer.isElementShown(allTypes[i])) { currentViewer.setSelection(new StructuredSelection(allTypes[i])); return; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } }
5,475
Bug 5475 F4 causes loss of context when called from a method view
1) Open a class with many methods 2) Make sure "show of source element only" is selected 3) Choose a method 4) Press F4 with no selection The class is open on the hierarchy view and the full source is shown in the editor. The method focus was lost. You have to find and select the method again.
resolved fixed
798e9a2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T10:51:58Z"
"2001-11-02T16:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewer.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; import org.eclipse.jdt.internal.ui.actions.OpenJavaElementAction; import org.eclipse.jdt.internal.ui.actions.ShowInPackageViewAction; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.MarkerErrorTickProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.internal.ui.wizards.NewGroup; public abstract class TypeHierarchyViewer extends ProblemTreeViewer implements IProblemChangedListener { private OpenJavaElementAction fOpen; private ShowInPackageViewAction fShowInPackageViewAction; private ContextMenuGroup[] fStandardGroups; public TypeHierarchyViewer(Composite parent, IContentProvider contentProvider, ILabelProvider lprovider, IWorkbenchPart part) { super(new Tree(parent, SWT.SINGLE)); setContentProvider(contentProvider); setLabelProvider(lprovider); setSorter(new ViewerSorter() { public boolean isSorterProperty(Object element, Object property) { return true; } public int category(Object element) { if (element instanceof IType) { try { return (((IType)element).isInterface()) ? 2 : 1; } catch (JavaModelException e) { } } else if (element instanceof IMember) { return 0; } return 3; } }); fOpen= new OpenJavaElementAction(this); addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { fOpen.run(); } }); fShowInPackageViewAction= new ShowInPackageViewAction(); fStandardGroups= new ContextMenuGroup[] { new JavaSearchGroup(), new NewGroup(), new GenerateGroup() }; } /** * Attaches a contextmenu listener to the tree */ public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) { MenuManager menuMgr= new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(menuListener); Menu menu= menuMgr.createContextMenu(getTree()); getTree().setMenu(menu); viewSite.registerContextMenu(popupId, menuMgr, this); } /** * Fills up the context menu with items for the hierarchy viewer * Should be called by the creator of the context menu */ public void contributeToContextMenu(IMenuManager menu) { if (fOpen.canActionBeAdded()) { menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen); } // XXX need to decide when to contribute the Show in PackagesView action // if (fShowInPackageViewAction.canOperateOn()) menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fShowInPackageViewAction); ContextMenuGroup.add(menu, fStandardGroups, this); } /** * Set the member filter */ public void setMemberFilter(IMember[] memberFilter) { getHierarchyContentProvider().setMemberFilter(memberFilter); } /** * Returns if method filtering is enabled. */ public boolean isMethodFiltering() { return getHierarchyContentProvider().getMemberFilter() != null; } /** * Returns true if the hierarchy contains elements. Returns one of them * With member filtering it is possible that no elements are visible */ public Object containsElements() { Object[] elements= ((IStructuredContentProvider)getContentProvider()).getElements(null); if (elements.length > 0) { return elements[0]; } return null; } /** * Returns true if the hierarchy contains element the element. */ public boolean isElementShown(Object element) { return findItem(element) != null; } /** * Updates the content of this viewer: refresh and expanding the tree in the way wanted. */ public abstract void updateContent(); /** * Returns the title for the current view */ public abstract String getTitle(); /* * @see StructuredViewer#setContentProvider * Content provider must be of type TypeHierarchyContentProvider */ public void setContentProvider(IContentProvider cp) { Assert.isTrue(cp instanceof TypeHierarchyContentProvider); super.setContentProvider(cp); } protected TypeHierarchyContentProvider getHierarchyContentProvider() { return (TypeHierarchyContentProvider)getContentProvider(); } }
3,622
Bug 3622 New Package Wizard has confusing message (1GD0L9O)
1. Create a new Java Project 2. Select the project. 3. Invoke New Java Package. Result: Before you type anything the following message appears at the top: "A folder corresponding to the package name already exists". At this point my package name field is empty. What does this message mean? Is this an error? If so, should it be displayed in red with the error icon? NOTES: EG (5/1/2001 5:53:41 AM) there should be no error message when the package name field is empty and finish should be disabled. MA (5/2/01 9:34:00 AM) It is a warning. I will remove the message EG (5/2/01 9:43:44 AM) issue how to create a default package? It can't be created by the user since it always there.
verified fixed
0870c24
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T11:05:19Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewPackageCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaConventions; 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.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; 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.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewPackageCreationWizardPage extends ContainerPage { private static final String PAGE_NAME= "NewPackageCreationWizardPage"; //$NON-NLS-1$ protected static final String PACKAGE= "NewPackageCreationWizardPage.package"; //$NON-NLS-1$ private StringDialogField fPackageDialogField; /** * Status of last validation of the package field */ protected IStatus fPackageStatus; private IPackageFragment fCreatedPackageFragment; public NewPackageCreationWizardPage(IWorkspaceRoot root) { super(PAGE_NAME, root); setTitle(NewWizardMessages.getString("NewPackageCreationWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewPackageCreationWizardPage.description")); //$NON-NLS-1$ fCreatedPackageFragment= null; PackageFieldAdapter adapter= new PackageFieldAdapter(); fPackageDialogField= new StringDialogField(); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewPackageCreationWizardPage.package.label")); //$NON-NLS-1$ fPackageStatus= new StatusInfo(); } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); setPackageText(""); //$NON-NLS-1$ updateStatus(findMostSevereStatus()); } // -------- UI Creation --------- /** * @see WizardPage#createControl */ public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int nColumns= 3; MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.minimumHeight= SWTUtil.convertHeightInCharsToPixels(20, composite); layout.numColumns= 3; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); fPackageDialogField.setFocus(); setControl(composite); WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.NEW_PACKAGE_WIZARD_PAGE)); } protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); } // -------- PackageFieldAdapter -------- private class PackageFieldAdapter implements IDialogFieldListener { // --------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { fPackageStatus= packageChanged(); // tell all others handleFieldChanged(PACKAGE); } } // -------- update message ---------------- /** * Called when a dialog field on this page changed * @see ContainerPage#fieldUpdated */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); } // do status line update updateStatus(findMostSevereStatus()); } /** * Finds the most severe error (if there is one) */ protected IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fContainerStatus, fPackageStatus); } // ----------- validation ---------- /** * Verify the input for the package field */ private IStatus packageChanged() { StatusInfo status= new StatusInfo(); String packName= fPackageDialogField.getText(); if (!"".equals(packName)) { //$NON-NLS-1$ IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewPackageCreationWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewPackageCreationWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ } } else { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.DefaultPackageExists")); //$NON-NLS-1$ return status; } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getUnderlyingResource().getFullPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.IsOutputFolder")); //$NON-NLS-1$ return status; } } if (pack.exists()) { if (pack.containsJavaResources() || !pack.hasSubpackages()) { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.PackageExists")); //$NON-NLS-1$ } else { status.setWarning(NewWizardMessages.getString("NewPackageCreationWizardPage.warning.PackageNotShown")); //$NON-NLS-1$ } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } return status; } protected String getPackageText() { return fPackageDialogField.getText(); } protected void setPackageText(String str) { fPackageDialogField.setText(str); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { createPackage(monitor); } catch (JavaModelException e) { throw new InvocationTargetException(e); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } public IPackageFragment getNewPackageFragment() { return fCreatedPackageFragment; } protected void createPackage(IProgressMonitor monitor) throws JavaModelException, CoreException, InterruptedException { IPackageFragmentRoot root= getPackageFragmentRoot(); String packName= getPackageText(); fCreatedPackageFragment= root.createPackageFragment(packName, true, monitor); } }
5,449
Bug 5449 TVT Text Expansion/Truncations in new java class dialog
null
resolved fixed
24c773c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T14:06:41Z"
"2001-11-02T00:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HistoryListAction.java
package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.Arrays; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class HistoryListAction extends Action { private class HistoryListDialog extends StatusDialog { private ListDialogField fHistoryList; private IStatus fHistoryStatus; private IJavaElement fResult; private HistoryListDialog(Shell shell, IJavaElement[] elements) { super(shell); setTitle(TypeHierarchyMessages.getString("HistoryListDialog.title")); String[] buttonLabels= new String[] { /* 0 */ TypeHierarchyMessages.getString("HistoryListDialog.remove.button") //$NON-NLS-1$ }; IListAdapter adapter= new IListAdapter() { public void customButtonPressed(DialogField field, int index) { } public void selectionChanged(DialogField field) { doSelectionChanged(); } }; JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT); fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider); fHistoryList.setLabelText(TypeHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$ fHistoryList.setRemoveButtonIndex(0); fHistoryList.setElements(Arrays.asList(elements)); ISelection sel; if (elements.length > 0) { sel= new StructuredSelection(elements[0]); } else { sel= new StructuredSelection(); } fHistoryList.selectElements(sel); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); int minimalWidth= convertWidthInCharsToPixels(80); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fHistoryList }, true, minimalWidth, 0, SWT.DEFAULT, SWT.DEFAULT); fHistoryList.getTableViewer().addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (fHistoryStatus.isOK()) { okPressed(); } } }); return composite; } private void doSelectionChanged() { StatusInfo status= new StatusInfo(); List selected= fHistoryList.getSelectedElements(); if (selected.size() != 1) { status.setError(""); fResult= null; } else { fResult= (IJavaElement) selected.get(0); } fHistoryStatus= status; updateStatus(status); } public IJavaElement getResult() { return fResult; } public IJavaElement[] getRemaining() { List elems= fHistoryList.getElements(); return (IJavaElement[]) elems.toArray(new IJavaElement[elems.size()]); } } private TypeHierarchyViewPart fView; public HistoryListAction(TypeHierarchyViewPart view) { fView= view; setText(TypeHierarchyMessages.getString("HistoryListAction.label")); JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$ } /* * @see IAction#run() */ public void run() { IJavaElement[] historyEntries= fView.getHistoryEntries(); HistoryListDialog dialog= new HistoryListDialog(JavaPlugin.getActiveWorkbenchShell(), historyEntries); if (dialog.open() == dialog.OK) { fView.setHistoryEntries(dialog.getRemaining()); fView.setInputElement(dialog.getResult()); } } }
5,449
Bug 5449 TVT Text Expansion/Truncations in new java class dialog
null
resolved fixed
24c773c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T14:06:41Z"
"2001-11-02T00:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.IInputSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.help.ViewContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.compare.JavaReplaceWithEditionAction; import org.eclipse.jdt.internal.ui.dnd.BasicSelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.BuildGroup; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.MarkerErrorTickProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of inut elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private IProblemChangedListener fHierarchyProblemListener; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private MethodsViewer fMethodsViewer; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private boolean fIsEnableMemberFilter; private SashForm fTypeMethodsSplitter; private PageBook fViewerbook; private PageBook fPagebook; private Label fNoHierarchyShownLabel; private Label fEmptyTypesViewer; private ViewForm fTypeViewerViewForm; private ViewForm fMethodViewerViewForm; private CLabel fMethodViewerPaneLabel; private JavaElementLabelProvider fPaneLabelProvider; private IDialogSettings fDialogSettings; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private int fCurrentOrientation; private EnableMemberFilterAction fEnableMemberFilterAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private IPartListener fPartListener; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fHierarchyProblemListener= null; fIsEnableMemberFilter= false; fInputHistory= new ArrayList(); fAllViewers= null; fViewActions= new ToggleViewAction[] { new ToggleViewAction(this, VIEW_ID_TYPE), new ToggleViewAction(this, VIEW_ID_SUPER), new ToggleViewAction(this, VIEW_ID_SUB) }; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); fHistoryDropDownAction= new HistoryDropDownAction(this); fToggleOrientationActions= new ToggleOrientationAction[] { new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE) }; fEnableMemberFilterAction= new EnableMemberFilterAction(this, false); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS); fPaneLabelProvider.setErrorTickManager(new MarkerErrorTickProvider()); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) {} public void partClosed(IWorkbenchPart part) {} public void partDeactivated(IWorkbenchPart part) {} public void partOpened(IWorkbenchPart part) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; } /** * Adds the entry if new. Inserted at the beginning of the history entries list. */ private void addHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { fInputHistory.remove(entry); } fInputHistory.add(0, entry); } private void updateHistoryEntries() { for (int i= fInputHistory.size() - 1; i >= 0; i--) { IJavaElement type= (IJavaElement) fInputHistory.get(i); if (!type.exists()) { fInputHistory.remove(i); } } } /** * 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() { 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 */ public void selectMember(IMember member) { ICompilationUnit cu= member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { member= (IMember) cu.getOriginal(member); if (member == null) { return; } } Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { fMethodsViewer.getControl().setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } /** * @deprecated */ public IType getInput() { if (fInputElement instanceof IType) { return (IType) fInputElement; } return null; } /** * Sets the input to a new type * @deprecated */ public void setInput(IType type) { setInputElement(type); } /** * Returns the input element of the type hierarchy. * Can be of type <code>IType</code> or <code>IPackageFragment</code> */ public IJavaElement getInputElement() { return fInputElement; } /** * Sets the input to a new element. */ public void setInputElement(IJavaElement element) { if (element != null) { if (element instanceof IMember) { ICompilationUnit cu= ((IMember) element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { element= cu.getOriginal(element); } if (element.getElementType() == IJavaElement.METHOD || element.getElementType() == IJavaElement.FIELD || element.getElementType() == IJavaElement.INITIALIZER) { element= ((IMember) element).getDeclaringType(); } } } if (element != null && !element.equals(fInputElement)) { addHistoryEntry(element); } updateInput(element); } /** * Changes the input to a new type */ private void updateInput(IJavaElement inputElement) { IJavaElement prevInput= fInputElement; fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { // turn off member filtering enableMemberFilter(false); try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } fPagebook.showPage(fTypeMethodsSplitter); if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } IType root= getSelectableType(fInputElement); internalSelectType(root); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); } } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); getSite().getPage().removePartListener(fPartListener); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } if (fMethodsViewer != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fMethodsViewer); } super.dispose(); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); KeyListener keyListener= createKeyListener(); HierarchyLabelProvider lprovider= new HierarchyLabelProvider(this, new MarkerErrorTickProvider()); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this); initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this); initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, 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 keyPressed(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F4) { OpenTypeHierarchyUtil.open(getSite().getSelectionProvider().getSelection(), getSite().getWorkbenchWindow()); return; } else if (event.keyCode == SWT.F5) { updateHierarchyViewer(); return; } } viewPartKeyShortcuts(event); } }; } private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) { typesViewer.getControl().setVisible(false); typesViewer.getControl().addKeyListener(keyListener); typesViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillTypesViewerContextMenu(typesViewer, menu); } }, cotextHelpId, getSite()); typesViewer.addSelectionChangedListener(fSelectionChangedListener); } private Control createMethodViewerControl(Composite parent) { fMethodsViewer= new MethodsViewer(parent, this); fMethodsViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillMethodsViewerContextMenu(menu); } }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite()); fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener); Control control= fMethodsViewer.getTable(); control.addKeyListener(createKeyListener()); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fMethodsViewer); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_COPY; DragSource source= new DragSource(fMethodsViewer.getControl(), ops); source.setTransfer(transfers); source.addDragListener(new BasicSelectionTransferDragAdapter(fMethodsViewer)); for (int i= 0; i < fAllViewers.length; i++) { TypeHierarchyViewer curr= fAllViewers[i]; curr.addDropSupport(ops, transfers, new TypeHierarchyTransferDropAdapter(curr)); } } private void viewPartKeyShortcuts(KeyEvent event) { if (event.stateMask == SWT.CTRL) { if (event.character == '1') { setView(VIEW_ID_TYPE); } else if (event.character == '2') { setView(VIEW_ID_SUPER); } else if (event.character == '3') { setView(VIEW_ID_SUB); } } } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); initDragAndDrop(); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ MenuManager menu= new MenuManager(); menu.add(fFocusOnTypeAction); fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel)); fPagebook.showPage(fNoHierarchyShownLabel); int orientation; try { orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION); if (orientation < 0 || orientation > 2) { orientation= VIEW_ORIENTATION_VERTICAL; } } catch (NumberFormatException e) { orientation= VIEW_ORIENTATION_VERTICAL; } // force the update fCurrentOrientation= -1; // will fill the main tool bar setOrientation(orientation); // set the filter menu items IActionBars actionBars= getViewSite().getActionBars(); IMenuManager viewMenu= actionBars.getMenuManager(); for (int i= 0; i < fToggleOrientationActions.length; i++) { viewMenu.add(fToggleOrientationActions[i]); } viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); // fill the method viewer toolbar ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar); lowertbmanager.add(fEnableMemberFilterAction); lowertbmanager.add(new Separator()); fMethodsViewer.contributeToToolBar(lowertbmanager); lowertbmanager.update(true); // selection provider int nHierarchyViewers= fAllViewers.length; Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1]; for (int i= 0; i < nHierarchyViewers; i++) { trackedViewers[i]= fAllViewers[i]; } trackedViewers[nHierarchyViewers]= fMethodsViewer; fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager)); getSite().setSelectionProvider(fSelectionProviderMediator); getSite().getPage().addPartListener(fPartListener); IJavaElement input= determineInputElement(); if (fMemento != null) { restoreState(fMemento, input); } else if (input != null) { setInputElement(input); } else { setViewerVisibility(false); } // fixed for 1GETAYN: ITPJUI:WIN - F1 help does nothing WorkbenchHelp.setHelp(fPagebook, new ViewContextComputer(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW)); } /** * called from ToggleOrientationAction. * @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL */ public void setOrientation(int orientation) { if (fCurrentOrientation != orientation) { boolean methodViewerNeedsUpdate= false; if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed() && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) { if (orientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(false); enableMemberFilter(false); updateMethodViewer(null); } else { if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(true); methodViewerNeedsUpdate= true; } boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL; fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL); updateMainToolbar(horizontal); } 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(boolean horizontal) { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager tbmanager= actionBars.getToolBarManager(); if (horizontal) { clearMainToolBar(tbmanager); ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP); fillMainToolBar(new ToolBarManager(typeViewerToolBar)); fTypeViewerViewForm.setTopLeft(typeViewerToolBar); } else { fTypeViewerViewForm.setTopLeft(null); fillMainToolBar(tbmanager); } } private void fillMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.add(fHistoryDropDownAction); for (int i= 0; i < fViewActions.length; i++) { tbmanager.add(fViewActions[i]); } tbmanager.update(false); } private void clearMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.update(false); } /** * Creates the context menu for the hierarchy viewers */ private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries viewer.contributeToContextMenu(menu); IStructuredSelection selection= (IStructuredSelection)viewer.getSelection(); if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { addOpenPerspectiveItem(menu, selection); } addOpenWithMenu(menu, selection); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnTypeAction); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnSelectionAction); addRefactoring(menu, viewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, viewer); } /** * Creates the context menu for the method viewer */ private void fillMethodsViewerContextMenu(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries fMethodsViewer.contributeToContextMenu(menu); if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) { menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction); } menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer)); addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection()); addRefactoring(menu, fMethodsViewer); ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, fMethodsViewer); } private void addRefactoring(IMenuManager menu, IInputSelectionProvider viewer){ MenuManager refactoring= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.refactor")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, viewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IJavaElement)) return; IResource resource= null; try { resource= ((IJavaElement)element).getUnderlyingResource(); } catch(JavaModelException e) { // ignore } if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } private void addOpenPerspectiveItem(IMenuManager menu, IStructuredSelection selection) { OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, selection); } /** * Toggles between the empty viewer page and the hierarchy */ private void setViewerVisibility(boolean showHierarchy) { if (showHierarchy) { fViewerbook.showPage(getCurrentViewer().getControl()); } else { fViewerbook.showPage(fEmptyTypesViewer); } } /** * Sets the member filter. <code>null</code> disables member filtering. */ private void setMemberFilter(IMember[] memberFilter) { Assert.isNotNull(fAllViewers); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setMemberFilter(memberFilter); } updateHierarchyViewer(); updateTitle(); } private IType getSelectableType(IJavaElement elem) { ISelection sel= null; if (elem.getElementType() != IJavaElement.TYPE) { return (IType) getCurrentViewer().getTreeRootType(); } else { return (IType) elem; } } private void internalSelectType(IMember elem) { TypeHierarchyViewer viewer= getCurrentViewer(); viewer.removeSelectionChangedListener(fSelectionChangedListener); viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY); viewer.addSelectionChangedListener(fSelectionChangedListener); } private void internalSelectMember(IMember member) { fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener); fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY); fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener); } /** * When the input changed or the hierarchy pane becomes visible, * <code>updateHierarchyViewer<code> brings up the correct view and refreshes * the current tree */ private void updateHierarchyViewer() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); } }; BusyIndicator.showWhile(getDisplay(), runnable); if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) { setViewerVisibility(true); } } else { fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$ setViewerVisibility(false); } } } private void updateMethodViewer(IType input) { if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } fMethodsViewer.setInput(input); } } private void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); } else { typeSelectionChanged(e.getSelection()); } } private void methodSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (fIsEnableMemberFilter) { IMember[] memberFilter= null; if (nSelected > 0) { memberFilter= new IMember[nSelected]; selected.toArray(memberFilter); } setMemberFilter(memberFilter); } if (nSelected == 1) { revealElementInEditor(selected.get(0), fMethodsViewer); } } } private void typeSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (nSelected != 0) { List types= new ArrayList(nSelected); for (int i= nSelected-1; i >= 0; i--) { Object elem= selected.get(i); if (elem instanceof IType && !types.contains(elem)) { types.add(elem); } } if (types.size() == 1) { fSelectedType= (IType) types.get(0); updateMethodViewer(fSelectedType); } else if (types.size() == 0) { // method selected, no change } if (nSelected == 1) { revealElementInEditor(selected.get(0), getCurrentViewer()); } } else { fSelectedType= null; updateMethodViewer(null); } } } private void revealElementInEditor(Object elem, Viewer originViewer) { // only allow revealing when the type hierarchy is the active pagae // no revealing after selection events due to model changes if (getSite().getPage().getActivePart() != this) { return; } if (fSelectionProviderMediator.getViewerInFocus() != originViewer) { return; } IEditorPart editorPart= EditorUtility.isOpenInEditor(elem); if (editorPart != null && (elem instanceof IJavaElement)) { try { getSite().getPage().removePartListener(fPartListener); EditorUtility.openInEditor(elem, false); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } catch (CoreException e) { JavaPlugin.log(e); } } } private Display getDisplay() { if (fPagebook != null && !fPagebook.isDisposed()) { return fPagebook.getDisplay(); } return null; } private boolean isChildVisible(Composite pb, Control child) { Control[] children= pb.getChildren(); for (int i= 0; i < children.length; i++) { if (children[i] == child && children[i].isVisible()) return true; } return false; } private void updateTitle() { String viewerTitle= getCurrentViewer().getTitle(); String tooltip; String title; if (fInputElement != null) { String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) }; title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$ tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$ } else { title= viewerTitle; tooltip= viewerTitle; } setTitle(title); setTitleToolTip(tooltip); } private void updateToolbarButtons() { boolean isType= fInputElement instanceof IType; for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; if (action.getViewerIndex() == VIEW_ID_TYPE) { action.setEnabled(fInputElement != null); } else { action.setEnabled(isType); } } } /** * Sets the current view (see view id) * called from ToggleViewAction. Must be called after creation of the viewpart. */ public void setView(int viewerIndex) { Assert.isNotNull(fAllViewers); if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) { fCurrentViewerIndex= viewerIndex; updateHierarchyViewer(); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { internalSelectType(getSelectableType(fInputElement)); } if (!fIsEnableMemberFilter) { typeSelectionChanged(currSelection); } } updateTitle(); if (fHierarchyProblemListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener); } fHierarchyProblemListener= getCurrentViewer(); JavaPlugin.getDefault().getProblemMarkerManager().addListener(fHierarchyProblemListener); fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex); getCurrentViewer().getTree().setFocus(); } for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; action.setChecked(fCurrentViewerIndex == action.getViewerIndex()); } } /** * Gets the curret active view index. */ public int getViewIndex() { return fCurrentViewerIndex; } private TypeHierarchyViewer getCurrentViewer() { return fAllViewers[fCurrentViewerIndex]; } /** * called from EnableMemberFilterAction. * Must be called after creation of the viewpart. */ public void enableMemberFilter(boolean on) { if (on != fIsEnableMemberFilter) { fIsEnableMemberFilter= on; if (!on) { IType methodViewerInput= (IType) fMethodsViewer.getInput(); setMemberFilter(null); if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) { // avoid that the method view changes content by selecting the previous input internalSelectType(methodViewerInput); } else if (fSelectedType != null) { // choose a input that exists internalSelectType(fSelectedType); updateMethodViewer(fSelectedType); } } else { methodSelectionChanged(fMethodsViewer.getSelection()); } } fEnableMemberFilterAction.setChecked(on); } /** * Called from ITypeHierarchyLifeCycleListener. * Can be called from any thread */ private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { doTypeHierarchyChangedOnViewers(changedTypes); } }); } } private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (changedTypes == null) { // hierarchy change if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } updateHierarchyViewer(); } } else { // elements in hierarchy modified if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { return (IJavaElement) input; } return null; } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { memento.putString(TAG_INPUT, fInputElement.getHandleIdentifier()); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fMethodsViewer.saveState(memento); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (!input.exists()) { input= null; } } setInputElement(input); Integer viewerIndex= memento.getInteger(TAG_VIEW); if (viewerIndex != null) { setView(viewerIndex.intValue()); } Integer orientation= memento.getInteger(TAG_ORIENTATION); if (orientation != null) { setOrientation(orientation.intValue()); } Integer ratio= memento.getInteger(TAG_RATIO); if (ratio != null) { fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() }); } ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } String selectionId= memento.getString(TAG_SELECTION); if (selectionId != null) { IJavaElement elem= JavaCore.create(selectionId); if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) { internalSelectType((IMember)elem); } } fMethodsViewer.restoreState(memento); } /** * Link selection to active editor. */ private void editorActivated(IEditorPart editor) { if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) { return; } if (fInputElement == null) { // no type hierarchy shown return; } IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class); try { TypeHierarchyViewer currentViewer= getCurrentViewer(); if (elem instanceof IClassFile) { IType type= ((IClassFile)elem).getType(); if (currentViewer.isElementShown(type)) { internalSelectType(type); 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]); updateMethodViewer(allTypes[i]); return; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } }
5,449
Bug 5449 TVT Text Expansion/Truncations in new java class dialog
null
resolved fixed
24c773c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T14:06:41Z"
"2001-11-02T00:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/TypePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.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.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.compiler.env.IConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.StubUtility; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; /** * <code>TypePage</code> contains controls and validation routines for a 'New Type WizardPage' * Implementors decide which components to add and to enable. Implementors can also * customize the validation code. * <code>TypePage</code> is intended to serve as base class of all wizards that create types. * Applets, Servlets, Classes, Interfaces... * See <code>NewClassCreationWizardPage</code> or <code>NewInterfaceCreationWizardPage</code> for an * example usage of TypePage. */ public abstract class TypePage extends ContainerPage { private final static String PAGE_NAME= "TypePage"; //$NON-NLS-1$ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPlugin.getDefault().getImageRegistry().get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; public TypePage(boolean isClass, String pageName, IWorkspaceRoot root) { super(pageName, root); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("TypePage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("TypePage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("TypePage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("TypePage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("TypePage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("TypePage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("TypePage.interfaces.class.label") : NewWizardMessages.getString("TypePage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("TypePage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("TypePage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("TypePage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("TypePage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("TypePage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the type page with a given * Java element as selection. * @param elem The initial selection of this page or null if no * selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= JavaModelUtil.findPrimaryType(cu); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { initializeDialogUnits(composite); (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, 4); } /** * Creates the controls for the enclosing type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { fEnclosingTypeSelection.doFillIntoGrid(composite, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); c.setLayoutData(new MGridData(MGridData.FILL_HORIZONTAL)); LayoutUtil.setHorizontalSpan(c, 2); c= fEnclosingTypeDialogField.getChangeControl(composite); c.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); } /** * Creates the controls for the type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); } /** * Creates the controls for the modifiers radio/ceckbox buttons. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); LayoutUtil.setHorizontalSpan(fAccMdfButtons.getSelectionButtonsGroup(composite), nColumns - 2); int minWidthHint= convertWidthInCharsToPixels(15); fAccMdfButtons.setButtonsMinWidth(minWidthHint); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); LayoutUtil.setHorizontalSpan(fOtherMdfButtons.getSelectionButtonsGroup(composite), nColumns - 2); fOtherMdfButtons.setButtonsMinWidth(minWidthHint); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { initializeDialogUnits(composite); fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); MGridData gd= (MGridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; } /** * Sets the focus on the container if empty, elso on type name. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /** * Called whenever a content of a field has changed. * Implementors of TypePage can hook in. * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Gets the text of package field. */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Gets the text of enclosing type field. */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * @return Returns <code>null</code> if the input could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the package fragment can be changed by the user */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the encloding type corresponding to the current input. * @return Returns <code>null</code> if enclosing type is not selected or the input could not * be resolved. */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the enclosing type can be changed by the user */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns <code>true</code> if the enclosing type selection check box is enabled. */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type selection checkbox. * @param canBeModified Selects if the enclosing type selection can be changed by the user */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Gets the type name. */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Gets the selected modifiers. * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= IConstants.AccPublic; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= IConstants.AccPrivate; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= IConstants.AccProtected; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= IConstants.AccAbstract; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= IConstants.AccFinal; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= IConstants.AccStatic; } return mdf; } /** * Sets the modifiers. * @param canBeModified Selects if the modifiers can be changed by the user * @see IConstants */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Gets the content of the super class text field. */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * @param canBeModified Selects if the super class can be changed by the user */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Gets the currently chosen super interfaces. * @return returns a list of String */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * @param interfacesNames a list of String */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * Called when the package field has changed. * The method validates the package name and returns the status of the validation * This also updates the package fragment model. * Can be extended to add more validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getUnderlyingResource().getFullPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("TypePage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass } fCurrPackage= pack; } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= fPackageDialogField.getText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Called when the enclosing type name has changed. * The method validates the enclosing type and returns the status of the validation * This also updates the enclosing type model. * Can be extended to add more validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= JavaModelUtil.findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); return status; } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("TypePage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Called when the superclass name has changed. * The method validates the superclass name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (!val.isOK()) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("TypePage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, sclassName); } } return type; } /** * Called when the list of super interface has changed. * The method validates the superinterfaces and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= JavaModelUtil.findType(root.getJavaProject(), intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass, checking is an extra } } } return status; } /** * Called when the modifiers have changed. * The method validates the modifiers and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("TypePage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null) { packages= froot.getChildren(); } } catch (JavaModelException e) { } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("TypePage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); if (fCurrPackage != null) { dialog.setInitialSelections(new Object[] { fCurrPackage }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_TYPES); dialog.setTitle(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ if (fCurrEnclosingType != null) { dialog.setInitialSelections(new Object[] { fCurrEnclosingType }); dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1)); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES); dialog.setTitle(NewWizardMessages.getString("TypePage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.SuperClassDialog.message")); //$NON-NLS-1$ if (fSuperClass != null) { dialog.setFilter(fSuperClass.getElementName()); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(NewWizardMessages.getString("TypePage.InterfacesDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("TypePage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= fTypeNameDialogField.getText(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); lineDelimiter= StubUtility.getLineDelimiterUsed(parentCU); String content= createTypeBody(imports, lineDelimiter); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); String content= createTypeBody(imports, lineDelimiter); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so the type can be parsed correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1)); if (methods.length > 0) { for (int i= 0; i < methods.length; i++) { createdType.createMethod(methods[i], null, false, null); } // add imports imports.create(!isInnerClass, null); } monitor.worked(1); String formattedContent= StubUtility.codeFormat(createdType.getSource(), indent, lineDelimiter); ISourceRange range= createdType.getSourceRange(); IBuffer buf= createdType.getCompilationUnit().getBuffer(); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. Only valid after createType has been invoked */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, IImportsStructure imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ buf.append(Signature.getSimpleName(typename)); if (fSuperClass != null) { imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass)); } else { imports.addImport(typename); } } } private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); imports.addImport(typename); buf.append(Signature.getSimpleName(typename)); if (i < last) { buf.append(", "); //$NON-NLS-1$ } } } } /* * Called from createType to construct the source for this type */ private String createTypeBody(IImportsStructure imports, String lineDelimiter) { StringBuffer buf= new StringBuffer(); int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append(" {"); //$NON-NLS-1$ buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * Called from createType to allow adding methods for the newly created type * Returns array of sources of the methods that have to be added * @param parent The type where the methods will be added to */ protected String[] evalMethods(IType parent, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return new String[0]; } /** * Creates the bodies of all unimplemented methods or/and all constructors * Can be used by implementors of TypePage to add method stub checkboxes */ protected String[] constructInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { StubUtility.evalConstructors(type, superclass, newMethods, imports); } } if (doUnimplementedMethods) { StubUtility.evalUnimplementedMethods(type, hierarchy, false, newMethods, imports); } return (String[]) newMethods.toArray(new String[newMethods.size()]); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
5,449
Bug 5449 TVT Text Expansion/Truncations in new java class dialog
null
resolved fixed
24c773c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T14:06:41Z"
"2001-11-02T00:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class VariableBlock { private ListDialogField fVariablesList; private StatusInfo fSelectionStatus; private IStatusChangeListener fContext; private boolean fUseAsSelectionDialog; private boolean fRemovingSelection= false; private String fSelectedVariable; private Control fControl; /** * Constructor for VariableBlock */ public VariableBlock(IStatusChangeListener context, boolean useAsSelectionDialog, String initSelection) { fContext= context; fUseAsSelectionDialog= useAsSelectionDialog; fSelectionStatus= new StatusInfo(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("VariableBlock.vars.add.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("VariableBlock.vars.edit.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("VariableBlock.vars.remove.button") //$NON-NLS-1$ }; VariablesAdapter adapter= new VariablesAdapter(); CPVariableElementLabelProvider labelProvider= new CPVariableElementLabelProvider(useAsSelectionDialog); fVariablesList= new ListDialogField(adapter, buttonLabels, labelProvider); fVariablesList.setDialogFieldListener(adapter); fVariablesList.setLabelText(NewWizardMessages.getString("VariableBlock.vars.label")); //$NON-NLS-1$ fVariablesList.setRemoveButtonIndex(3); fVariablesList.enableButton(1, false); CPVariableElement initSelectedElement= null; String[] reservedName= getReservedVariableNames(); ArrayList reserved= new ArrayList(reservedName.length); addAll(reservedName, reserved); String[] entries= JavaCore.getClasspathVariableNames(); ArrayList elements= new ArrayList(entries.length); for (int i= 0; i < entries.length; i++) { String name= entries[i]; CPVariableElement elem; IPath entryPath= JavaCore.getClasspathVariable(name); elem= new CPVariableElement(name, entryPath, reserved.contains(name)); elements.add(elem); if (name.equals(initSelection)) { initSelectedElement= elem; } } fVariablesList.setElements(elements); ISelection sel; if (initSelectedElement != null) { sel= new StructuredSelection(initSelectedElement); } else if (entries.length > 0) { sel= new StructuredSelection(fVariablesList.getElement(0)); } else { sel= StructuredSelection.EMPTY; } fVariablesList.selectElements(sel); } private String[] getReservedVariableNames() { return new String[] { JavaRuntime.JRELIB_VARIABLE, JavaRuntime.JRESRC_VARIABLE, JavaRuntime.JRESRCROOT_VARIABLE, }; } public Control createContents(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int minimalWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fVariablesList }, true, minimalWidth, 0, 0, 0); fVariablesList.getTableViewer().setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof CPVariableElement && e2 instanceof CPVariableElement) { return ((CPVariableElement)e1).getName().compareTo(((CPVariableElement)e2).getName()); } return super.compare(viewer, e1, e2); } }); fControl= composite; return composite; } public void addDoubleClickListener(IDoubleClickListener listener) { fVariablesList.getTableViewer().addDoubleClickListener(listener); } private Shell getShell() { if (fControl != null) { return fControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } public String getSelectedVariable() { return fSelectedVariable; } private class VariablesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { switch (index) { case 0: /* add */ editEntries(null); break; case 1: /* edit */ List selected= fVariablesList.getSelectedElements(); editEntries((CPVariableElement)selected.get(0)); break; } } public void selectionChanged(DialogField field) { doSelectionChanged(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { } } private boolean containsReserved(List selected) { for (int i= selected.size()-1; i >= 0; i--) { if (((CPVariableElement)selected.get(i)).isReserved()) { return true; } } return false; } private static void addAll(Object[] objs, Collection dest) { for (int i= 0; i < objs.length; i++) { dest.add(objs[i]); } } private void doSelectionChanged(DialogField field) { List selected= fVariablesList.getSelectedElements(); boolean isSingleSelected= selected.size() == 1; boolean containsReserved= containsReserved(selected); // edit fVariablesList.enableButton(1, isSingleSelected && !containsReserved); // remove button fVariablesList.enableButton(3, !containsReserved); fSelectedVariable= null; if (fUseAsSelectionDialog) { if (isSingleSelected) { fSelectionStatus.setOK(); fSelectedVariable= ((CPVariableElement)selected.get(0)).getName(); } else { fSelectionStatus.setError(""); //$NON-NLS-1$ } fContext.statusChanged(fSelectionStatus); } } private void editEntries(CPVariableElement entry) { List existingEntries= fVariablesList.getElements(); VariableCreationDialog dialog= new VariableCreationDialog(getShell(), entry, existingEntries); if (dialog.open() != dialog.OK) { return; } CPVariableElement newEntry= dialog.getClasspathElement(); if (entry == null) { fVariablesList.addElement(newEntry); entry= newEntry; } else { entry.setName(newEntry.getName()); entry.setPath(newEntry.getPath()); fVariablesList.refresh(); } fVariablesList.selectElements(new StructuredSelection(entry)); } public void performDefaults() { fVariablesList.removeAllElements(); String[] reservedName= getReservedVariableNames(); for (int i= 0; i < reservedName.length; i++) { CPVariableElement elem= new CPVariableElement(reservedName[i], null, true); elem.setReserved(true); fVariablesList.addElement(elem); } } public boolean performOk() { List toRemove= new ArrayList(); toRemove.addAll(Arrays.asList(JavaCore.getClasspathVariableNames())); // remove all unchanged List elements= fVariablesList.getElements(); for (int i= elements.size()-1; i >= 0; i--) { CPVariableElement curr= (CPVariableElement) elements.get(i); if (curr.isReserved()) { elements.remove(curr); } else { IPath path= curr.getPath(); IPath prevPath= JavaCore.getClasspathVariable(curr.getName()); if (prevPath != null && prevPath.equals(path)) { elements.remove(curr); } } toRemove.remove(curr.getName()); } int steps= elements.size() + toRemove.size(); if (steps > 0) { IRunnableWithProgress runnable= new VariableBlockRunnable(toRemove, elements); ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); try { dialog.run(true, true, runnable); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), NewWizardMessages.getString("VariableBlock.operation_errror.title"), NewWizardMessages.getString("VariableBlock.operation_errror.message")); return false; } catch (InterruptedException e) { return true; } } return true; } private class VariableBlockRunnable implements IRunnableWithProgress { private List fToRemove; private List fToChange; public VariableBlockRunnable(List toRemove, List toChange) { fToRemove= toRemove; fToChange= toChange; } /* * @see IRunnableWithProgress#run(IProgressMonitor) */ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int steps= fToChange.size() + fToRemove.size(); monitor.beginTask(NewWizardMessages.getString("VariableBlock.operation_desc"), steps); //$NON-NLS-1$ try { for (int i= 0; i < fToChange.size(); i++) { CPVariableElement curr= (CPVariableElement) fToChange.get(i); SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1); JavaCore.setClasspathVariable(curr.getName(), curr.getPath(), subMonitor); if (monitor.isCanceled()) { return; } } for (int i= 0; i < fToRemove.size(); i++) { SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1); JavaCore.removeClasspathVariable((String) fToRemove.get(i), subMonitor); if (monitor.isCanceled()) { return; } } } catch (JavaModelException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } } }
5,449
Bug 5449 TVT Text Expansion/Truncations in new java class dialog
null
resolved fixed
24c773c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T14:06:41Z"
"2001-11-02T00:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; 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.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; 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.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; /** * A list with a button bar. * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. * List model is independend of widget creation. * DialogFields controls are: Label, List and Composite containing buttons. */ public class ListDialogField extends DialogField { protected TableViewer fTable; protected ILabelProvider fLabelProvider; protected ListViewerAdapter fListViewerAdapter; protected List fElements; protected String[] fButtonLabels; private Button[] fButtonControls; private boolean[] fButtonsEnabled; private int fRemoveButtonIndex; private int fUpButtonIndex; private int fDownButtonIndex; private Label fLastSeparator; private Table fTableControl; private Composite fButtonsControl; private ISelection fSelectionWhenEnabled; private TableColumn fTableColumn; private IListAdapter fListAdapter; private Object fParentElement; /** * Creates the <code>ListDialogField</code>. * @param adapter A listener for button invocation, selection changes. * @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and * marks a separator. * @param lprovider The label provider to render the table entries */ public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) { super(); fListAdapter= adapter; fLabelProvider= lprovider; fListViewerAdapter= new ListViewerAdapter(); fParentElement= this; fElements= new ArrayList(10); fButtonLabels= buttonLabels; if (fButtonLabels != null) { int nButtons= fButtonLabels.length; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsEnabled[i]= true; } } fTable= null; fTableControl= null; fButtonsControl= null; fRemoveButtonIndex= -1; fUpButtonIndex= -1; fDownButtonIndex= -1; } /** * Sets the index of the 'remove' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'remove' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); fRemoveButtonIndex= removeButtonIndex; } /** * Sets the index of the 'up' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'up' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); fUpButtonIndex= upButtonIndex; } /** * Sets the index of the 'down' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'down' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); fDownButtonIndex= downButtonIndex; } // ------ adapter communication private void buttonPressed(int index) { if (!managedButtonPressed(index)) { fListAdapter.customButtonPressed(this, index); } } /** * Checks if the button pressed is handled internally * @return Returns true if button has been handled. */ protected boolean managedButtonPressed(int index) { if (index == fRemoveButtonIndex) { remove(); } else if (index == fUpButtonIndex) { up(); } else if (index == fDownButtonIndex) { down(); } else { return false; } return true; } // ------ layout helpers /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); Label label= getLabelControl(parent); MGridData gd= gridDataForLabel(1); gd.verticalAlignment= gd.BEGINNING; label.setLayoutData(gd); Control list= getListControl(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= true; gd.grabColumn= 0; gd.horizontalSpan= nColumns - 2; gd.widthHint= SWTUtil.convertWidthInCharsToPixels(40, list); gd.heightHint= SWTUtil.convertHeightInCharsToPixels(15, list); list.setLayoutData(gd); Composite buttons= getButtonBox(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= false; gd.horizontalSpan= 1; buttons.setLayoutData(gd); return new Control[] { label, list, buttons }; } /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { return 3; } /** * Sets the minimal width of the buttons. Must be called after widget creation. */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { ((MGridData)fLastSeparator.getLayoutData()).widthHint= minWidth; } } // ------ ui creation /** * Returns the list control. When called the first time, the control will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Control getListControl(Composite parent) { if (fTableControl == null) { assertCompositeNotNull(parent); fTable= createTableViewer(parent); fTable.setContentProvider(fListViewerAdapter); fTable.setLabelProvider(fLabelProvider); fTable.addSelectionChangedListener(fListViewerAdapter); fTableControl= (Table)fTable.getControl(); // Add a table column. TableLayout tableLayout= new TableLayout(); tableLayout.addColumnData(new ColumnWeightData(100)); fTableColumn= new TableColumn(fTableControl, SWT.NONE); fTableColumn.setResizable(false); fTableControl.setLayout(tableLayout); fTable.setInput(fParentElement); fTableControl.setEnabled(isEnabled()); if (fSelectionWhenEnabled != null) { postSetSelection(fSelectionWhenEnabled); } fTableColumn.getDisplay().asyncExec(new Runnable() { public void run() { if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } } }); } return fTableControl; } /** * Returns the internally used table viewer. */ public TableViewer getTableViewer() { return fTable; } /* * Subclasses may override to specify a different style. */ protected int getListStyle(){ return SWT.BORDER + SWT.MULTI + SWT.H_SCROLL + SWT.V_SCROLL; } protected TableViewer createTableViewer(Composite parent) { Table table= new Table(parent, getListStyle()); return new TableViewer(table); } protected Button createButton(Composite parent, String label, SelectionListener listener) { Button button= new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(listener); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.BEGINNING; gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); return button; } private Label createSeparator(Composite parent) { Label separator= new Label(parent, SWT.NONE); separator.setVisible(false); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.verticalAlignment= gd.BEGINNING; gd.heightHint= 4; separator.setLayoutData(gd); return separator; } /** * Returns the composite containing the buttons. When called the first time, the control * will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; Composite contents= new Composite(parent, SWT.NULL); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; contents.setLayout(layout); if (fButtonLabels != null) { fButtonControls= new Button[fButtonLabels.length]; for (int i= 0; i < fButtonLabels.length; i++) { String currLabel= fButtonLabels[i]; if (currLabel != null) { fButtonControls[i]= createButton(contents, currLabel, listener); fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); } else { fButtonControls[i]= null; createSeparator(contents); } } } fLastSeparator= createSeparator(contents); updateButtonState(); fButtonsControl= contents; } return fButtonsControl; } private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { for (int i= 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; } } } } // ------ enable / disable management /* * @see DialogField#dialogFieldChanged */ public void dialogFieldChanged() { super.dialogFieldChanged(); if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } updateButtonState(); } private Button getButton(int index) { if (fButtonControls != null && index >= 0 && index < fButtonControls.length) { return fButtonControls[index]; } return null; } /* * Updates the enable state of the all buttons */ protected void updateButtonState() { if (fButtonControls != null) { ISelection sel= fTable.getSelection(); for (int i= 0; i < fButtonControls.length; i++) { Button button= fButtonControls[i]; if (isOkToUse(button)) { boolean extraState= getManagedButtonState(sel, i); button.setEnabled(isEnabled() && extraState && fButtonsEnabled[i]); } } } } protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fRemoveButtonIndex) { return !sel.isEmpty(); } else if (index == fUpButtonIndex) { return !sel.isEmpty() && canMoveUp(); } else if (index == fDownButtonIndex) { return !sel.isEmpty() && canMoveDown(); } return true; } /* * @see DialogField#updateEnableState */ protected void updateEnableState() { super.updateEnableState(); boolean enabled= isEnabled(); if (isOkToUse(fTableControl)) { if (!enabled) { fSelectionWhenEnabled= fTable.getSelection(); selectElements(null); } else { selectElements(fSelectionWhenEnabled); fSelectionWhenEnabled= null; } fTableControl.setEnabled(enabled); } updateButtonState(); } /** * Sets a button enabled or disabled. */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { fButtonsEnabled[index]= enable; updateButtonState(); } } // ------ model access /** * Sets the elements shown in the list. */ public void setElements(List elements) { fElements= new ArrayList(elements); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } /** * Gets the elements shown in the list. * The list returned is a copy, so it can be modified by the user. */ public List getElements() { return new ArrayList(fElements); } /** * Gets the elements shown at the given index. */ public Object getElement(int index) { return fElements.get(index); } /** * Replace an element. */ public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException { int idx= fElements.indexOf(oldElement); if (idx != -1) { if (oldElement.equals(newElement) || fElements.contains(newElement)) { return; } fElements.set(idx, newElement); if (fTable != null) { List selected= getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } fTable.refresh(); fTable.setSelection(new StructuredSelection(selected)); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Adds an element at the end of the list. */ public void addElement(Object element) { if (fElements.contains(element)) { return; } fElements.add(element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds elements at the end of the list. */ public void addElements(List elements) { int nElements= elements.size(); if (nElements > 0) { // filter duplicated ArrayList elementsToAdd= new ArrayList(nElements); for (int i= 0; i < nElements; i++) { Object elem= elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); } } fElements.addAll(elementsToAdd); if (fTable != null) { fTable.add(elementsToAdd.toArray()); } dialogFieldChanged(); } } /** * Adds an element at a position. */ public void insertElementAt(Object element, int index) { if (fElements.contains(element)) { return; } fElements.add(index, element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds an element at a position. */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } } /** * Removes an element from the list. */ public void removeElement(Object element) throws IllegalArgumentException { if (fElements.remove(element)) { if (fTable != null) { fTable.remove(element); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Removes elements from the list. */ public void removeElements(List elements) { if (elements.size() > 0) { fElements.removeAll(elements); if (fTable != null) { fTable.remove(elements.toArray()); } dialogFieldChanged(); } } /** * Gets the number of elements */ public int getSize() { return fElements.size(); } public void selectElements(ISelection selection) { fSelectionWhenEnabled= selection; if (fTable != null) { fTable.setSelection(selection); } } public void postSetSelection(final ISelection selection) { if (isOkToUse(fTableControl)) { Display d= fTableControl.getDisplay(); d.asyncExec(new Runnable() { public void run() { if (isOkToUse(fTableControl)) { selectElements(selection); } } }); } } /** * Refreshes the table. */ public void refresh() { fTable.refresh(); } // ------- list maintenance private List moveUp(List elements, List move) { int nElements= elements.size(); List res= new ArrayList(nElements); Object floating= null; for (int i= 0; i < nElements; i++) { Object curr= elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } floating= curr; } } if (floating != null) { res.add(floating); } return res; } private void moveUp(List toMoveUp) { if (toMoveUp.size() > 0) { setElements(moveUp(fElements, toMoveUp)); fTable.reveal(toMoveUp.get(0)); } } private void moveDown(List toMoveDown) { if (toMoveDown.size() > 0) { setElements(reverse(moveUp(reverse(fElements), toMoveDown))); fTable.reveal(toMoveDown.get(toMoveDown.size() - 1)); } } private List reverse(List p) { List reverse= new ArrayList(p.size()); for (int i= p.size()-1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; } private void remove() { removeElements(getSelectedElements()); } private void up() { moveUp(getSelectedElements()); } private void down() { moveDown(getSelectedElements()); } private boolean canMoveUp() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); for (int i= 0; i < indc.length; i++) { if (indc[i] != i) { return true; } } } return false; } private boolean canMoveDown() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); int k= fElements.size() - 1; for (int i= indc.length - 1; i >= 0 ; i--, k--) { if (indc[i] != k) { return true; } } } return false; } /** * Returns the selected elements. */ public List getSelectedElements() { List result= new ArrayList(); if (fTable != null) { ISelection selection= fTable.getSelection(); if (selection instanceof IStructuredSelection) { Iterator iter= ((IStructuredSelection)selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } } } return result; } // ------- ListViewerAdapter private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener { // ------- ITableContentProvider Interface ------------ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // will never happen } public boolean isDeleted(Object element) { return false; } public void dispose() { } public Object[] getElements(Object obj) { return fElements.toArray(); } // ------- ISelectionChangedListener Interface ------------ public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } } private void doListSelected(SelectionChangedEvent event) { updateButtonState(); if (fListAdapter != null) { fListAdapter.selectionChanged(this); } } }
5,449
Bug 5449 TVT Text Expansion/Truncations in new java class dialog
null
resolved fixed
24c773c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T14:06:41Z"
"2001-11-02T00:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import org.eclipse.swt.SWT; 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.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; /** * Dialog field describing a group with buttons (Checkboxes, radio buttons..) */ public class SelectionButtonDialogFieldGroup extends DialogField { private Composite fButtonComposite; private Button[] fButtons; private String[] fButtonNames; private boolean[] fButtonsSelected; private boolean[] fButtonsEnabled; private int fGroupBorderStyle; private int fGroupNumberOfColumns; private int fButtonsStyle; /** * Creates a group without border. */ public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns) { this(buttonsStyle, buttonNames, nColumns, SWT.NONE); } /** * Creates a group with border (label in border). * Accepted button styles are: SWT.RADIO, SWT.CHECK, SWT.TOGGLE * For border styles see <code>Group</code> */ public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns, int borderStyle) { super(); Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE); fButtonNames= buttonNames; int nButtons= buttonNames.length; fButtonsSelected= new boolean[nButtons]; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsSelected[i]= false; fButtonsEnabled[i]= true; } if (fButtonsStyle == SWT.RADIO) { fButtonsSelected[0]= true; } fGroupBorderStyle= borderStyle; fGroupNumberOfColumns= (nColumns <= 0) ? nButtons : nColumns; fButtonsStyle= buttonsStyle; } // ------- layout helpers /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); if (fGroupBorderStyle == SWT.NONE) { Label label= getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); Composite buttonsgroup= getSelectionButtonsGroup(parent); MGridData gd= new MGridData(); gd.horizontalSpan= nColumns - 1; gd.grabColumn= 0; buttonsgroup.setLayoutData(gd); return new Control[] { label, buttonsgroup }; } else { Composite buttonsgroup= getSelectionButtonsGroup(parent); MGridData gd= new MGridData(); gd.horizontalSpan= nColumns; gd.grabColumn= 0; buttonsgroup.setLayoutData(gd); return new Control[] { buttonsgroup }; } } /* * @see DialogField#doFillIntoGrid */ public int getNumberOfControls() { return (fGroupBorderStyle == SWT.NONE) ? 2 : 1; } /** * Sets the minimal size of the buttons. Must be called after the creation of the buttons. */ public void setButtonsMinWidth(int minWidth) { if (fButtonComposite != null) { Control[] control= fButtonComposite.getChildren(); if (control != null && control.length > 0) { ((MGridData)control[0].getLayoutData()).widthHint= minWidth; } } } // ------- ui creation private Button createSelectionButton(int index, Composite group, SelectionListener listener) { Button button= new Button(group, fButtonsStyle | SWT.LEFT); button.setFont(group.getFont()); button.setText(fButtonNames[index]); button.setEnabled(isEnabled() && fButtonsEnabled[index]); button.setSelection(fButtonsSelected[index]); button.addSelectionListener(listener); button.setLayoutData(new MGridData()); return button; } /** * Returns the group widget. When called the first time, the widget will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getSelectionButtonsGroup(Composite parent) { if (fButtonComposite == null) { assertCompositeNotNull(parent); MGridLayout layout= new MGridLayout(); layout.makeColumnsEqualWidth= true; layout.numColumns= fGroupNumberOfColumns; if (fGroupBorderStyle != SWT.NONE) { Group group= new Group(parent, fGroupBorderStyle); if (fLabelText != null && fLabelText.length() > 0) { group.setText(fLabelText); } fButtonComposite= group; } else { fButtonComposite= new Composite(parent, SWT.NULL); layout.marginHeight= 0; layout.marginWidth= 0; } fButtonComposite.setLayout(layout); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doWidgetSelected(e); } public void widgetSelected(SelectionEvent e) { doWidgetSelected(e); } }; int nButtons= fButtonNames.length; fButtons= new Button[nButtons]; for (int i= 0; i < nButtons; i++) { fButtons[i]= createSelectionButton(i, fButtonComposite, listener); } int nRows= nButtons / fGroupNumberOfColumns; int nFillElements= nRows * fGroupNumberOfColumns - nButtons; for (int i= 0; i < nFillElements; i++) { createEmptySpace(fButtonComposite); } } return fButtonComposite; } /** * Returns a button from the group or <code>null</code> if not yet created. */ public Button getSelectionButton(int index) { if (index >= 0 && index < fButtons.length) { return fButtons[index]; } return null; } private void doWidgetSelected(SelectionEvent e) { Button button= (Button)e.widget; for (int i= 0; i < fButtons.length; i++) { if (fButtons[i] == button) { fButtonsSelected[i]= button.getSelection(); dialogFieldChanged(); return; } } } // ------ model access /** * Returns the selection state of a button contained in the group. * @param The index of the button */ public boolean isSelected(int index) { if (index >= 0 && index < fButtonsSelected.length) { return fButtonsSelected[index]; } return false; } /** * Sets the selection state of a button contained in the group. */ public void setSelection(int index, boolean selected) { if (index >= 0 && index < fButtonsSelected.length) { if (fButtonsSelected[index] != selected) { fButtonsSelected[index]= selected; if (fButtons != null) { Button button= fButtons[index]; if (isOkToUse(button)) { button.setSelection(selected); } } } } } // ------ enable / disable management protected void updateEnableState() { super.updateEnableState(); if (fButtons != null) { boolean enabled= isEnabled(); for (int i= 0; i < fButtons.length; i++) { Button button= fButtons[i]; if (isOkToUse(button)) { button.setEnabled(enabled && fButtonsEnabled[i]); } } } } /** * Sets the enable state of a button contained in the group. */ public void enableSelectionButton(int index, boolean enable) { if (index >= 0 && index < fButtonsEnabled.length) { fButtonsEnabled[index]= enable; if (fButtons != null) { Button button= fButtons[index]; if (isOkToUse(button)) { button.setEnabled(isEnabled() && enable); } } } } }
4,151
Bug 4151 Value hovering should show type name not only value (1GIYQVJ)
EG (24.08.2001 14:42:59) value hovering should show the runtime type in addition to the value NOTES:
resolved fixed
d26b1c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-22T14:22:34Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaDebugHover.java
package org.eclipse.jdt.internal.ui.text.java.hover; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.List; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.core.model.IVariable; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewer; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.debug.core.IJavaDebugTarget; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; public class JavaDebugHover implements ITextHover { protected IEditorPart fEditor; public JavaDebugHover(IEditorPart editor) { fEditor= editor; } /** * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } /** * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { DebugPlugin debugPlugin= DebugPlugin.getDefault(); if (debugPlugin == null) return null; ILaunchManager launchManager= debugPlugin.getLaunchManager(); if (launchManager == null) return null; IDebugTarget[] targets= launchManager.getDebugTargets(); if (targets != null && targets.length > 0) { try { String variableName= textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength()); boolean first= true; StringBuffer buffer= new StringBuffer(); for (int i= 0; i < targets.length; i++) { IJavaDebugTarget javaTarget = (IJavaDebugTarget) targets[i].getAdapter(IJavaDebugTarget.class); if (javaTarget != null) { try { IVariable variable= javaTarget.findVariable(variableName); if (variable != null) { if (!first) buffer.append('\n'); first= false; buffer.append(variable.getValue().getValueString()); } } catch (DebugException x) { } } } if (buffer.length() > 0) return buffer.toString(); } catch (BadLocationException x) { } } return null; } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeInputDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.util.HashMap; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; /** * Dialog to enter a new package entry in the organize import preference page. */ public class ImportOrganizeInputDialog extends StatusDialog { private class ImportOrganizeInputAdapter implements IDialogFieldListener, IStringButtonAdapter { /** * @see IDialogFieldListener#dialogFieldChanged(DialogField) */ public void dialogFieldChanged(DialogField field) { doValidation(); } /** * @see IStringButtonAdapter#changeControlPressed(DialogField) */ public void changeControlPressed(DialogField field) { doButtonPressed(); } } private StringButtonDialogField fNameDialogField; private List fExistingEntries; public ImportOrganizeInputDialog(Shell parent, List existingEntries) { super(parent); fExistingEntries= existingEntries; setTitle(JavaUIMessages.getString("ImportOrganizeInputDialog.title")); ImportOrganizeInputAdapter adapter= new ImportOrganizeInputAdapter(); fNameDialogField= new StringButtonDialogField(adapter); fNameDialogField.setLabelText(JavaUIMessages.getString("ImportOrganizeInputDialog.message")); fNameDialogField.setButtonLabel(JavaUIMessages.getString("ImportOrganizeInputDialog.browse.button")); fNameDialogField.setDialogFieldListener(adapter); } public void setInitialString(String input) { Assert.isNotNull(input); fNameDialogField.setText(input); } public Object getResult() { return fNameDialogField.getText(); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); int minimalWidth= convertWidthInCharsToPixels(80); LayoutUtil.doDefaultLayout(inner, new DialogField[] { fNameDialogField }, true, minimalWidth, 0, 0, 0); fNameDialogField.postSetFocusOnDialogField(parent.getDisplay()); return composite; } private void doButtonPressed() { HashMap allPackages= new HashMap(); // no duplicate entries try { IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); IJavaProject[] projects= JavaCore.create(root).getJavaProjects(); for (int i= 0; i < projects.length; i++) { IPackageFragment[] packs= projects[i].getPackageFragments(); for (int k=0; k < packs.length; k++) { IPackageFragment curr= packs[k]; // filter out default package and resource folders if (!curr.isDefaultPackage() && (curr.hasChildren() || curr.getNonJavaResources().length == 0)) { allPackages.put(curr.getElementName(), curr); } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } Object initialSelection= allPackages.get(fNameDialogField.getText()); ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(JavaUIMessages.getString("ImportOrganizeInputDialog.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(JavaUIMessages.getString("ImportOrganizeInputDialog.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(JavaUIMessages.getString("ImportOrganizeInputDialog.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(allPackages.values().toArray()); if (initialSelection != null) { dialog.setInitialSelections(new Object[] { initialSelection }); } if (dialog.open() == dialog.OK) { IPackageFragment res= (IPackageFragment) dialog.getFirstResult(); fNameDialogField.setText(res.getElementName()); } } private void doValidation() { StatusInfo status= new StatusInfo(); String newText= fNameDialogField.getText(); if (newText.length() == 0) { status.setError(JavaUIMessages.getString("ImportOrganizeInputDialog.error.enterName")); } else { IStatus val= JavaConventions.validatePackageName(newText); if (val.matches(IStatus.ERROR)) { status.setError(JavaUIMessages.getFormattedString("ImportOrganizeInputDialog.error.invalidName", val.getMessage())); } else { if (fExistingEntries.contains(newText)) { status.setError(JavaUIMessages.getString("ImportOrganizeInputDialog.error.entryExists")); } } } updateStatus(status); } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HistoryListAction.java
package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.Arrays; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class HistoryListAction extends Action { private class HistoryListDialog extends StatusDialog { private ListDialogField fHistoryList; private IStatus fHistoryStatus; private IJavaElement fResult; private HistoryListDialog(Shell shell, IJavaElement[] elements) { super(shell); setTitle(TypeHierarchyMessages.getString("HistoryListDialog.title")); String[] buttonLabels= new String[] { /* 0 */ TypeHierarchyMessages.getString("HistoryListDialog.remove.button") //$NON-NLS-1$ }; IListAdapter adapter= new IListAdapter() { public void customButtonPressed(DialogField field, int index) { } public void selectionChanged(DialogField field) { doSelectionChanged(); } }; JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT); fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider); fHistoryList.setLabelText(TypeHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$ fHistoryList.setRemoveButtonIndex(0); fHistoryList.setElements(Arrays.asList(elements)); ISelection sel; if (elements.length > 0) { sel= new StructuredSelection(elements[0]); } else { sel= new StructuredSelection(); } fHistoryList.selectElements(sel); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); int minimalWidth= convertWidthInCharsToPixels(80); int minimalHeight= convertHeightInCharsToPixels(20); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fHistoryList }, true, minimalWidth, minimalHeight, SWT.DEFAULT, SWT.DEFAULT); fHistoryList.getTableViewer().addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (fHistoryStatus.isOK()) { okPressed(); } } }); return composite; } private void doSelectionChanged() { StatusInfo status= new StatusInfo(); List selected= fHistoryList.getSelectedElements(); if (selected.size() != 1) { status.setError(""); fResult= null; } else { fResult= (IJavaElement) selected.get(0); } fHistoryStatus= status; updateStatus(status); } public IJavaElement getResult() { return fResult; } public IJavaElement[] getRemaining() { List elems= fHistoryList.getElements(); return (IJavaElement[]) elems.toArray(new IJavaElement[elems.size()]); } } private TypeHierarchyViewPart fView; public HistoryListAction(TypeHierarchyViewPart view) { fView= view; setText(TypeHierarchyMessages.getString("HistoryListAction.label")); JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$ } /* * @see IAction#run() */ public void run() { IJavaElement[] historyEntries= fView.getHistoryEntries(); HistoryListDialog dialog= new HistoryListDialog(JavaPlugin.getActiveWorkbenchShell(), historyEntries); if (dialog.open() == dialog.OK) { fView.setHistoryEntries(dialog.getRemaining()); fView.setInputElement(dialog.getResult()); } } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ContainerPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementContentProvider; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementSorter; 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.StringButtonDialogField; public abstract class ContainerPage extends NewElementWizardPage { /** * container field id */ protected static final String CONTAINER= "ContainerPage.container"; //$NON-NLS-1$ /** * Status of last validation */ protected IStatus fContainerStatus; private StringButtonDialogField fContainerDialogField; /* * package fragment root corresponding to the input type (can be null) */ private IPackageFragmentRoot fCurrRoot; private IWorkspaceRoot fWorkspaceRoot; public ContainerPage(String name, IWorkspaceRoot root) { super(name); fWorkspaceRoot= root; ContainerFieldAdapter adapter= new ContainerFieldAdapter(); fContainerDialogField= new StringButtonDialogField(adapter); fContainerDialogField.setDialogFieldListener(adapter); fContainerDialogField.setLabelText(NewWizardMessages.getString("ContainerPage.container.label")); //$NON-NLS-1$ fContainerDialogField.setButtonLabel(NewWizardMessages.getString("ContainerPage.container.button")); //$NON-NLS-1$ fContainerStatus= new StatusInfo(); fCurrRoot= null; } /** * Initializes the fields provided by the container page with a given * Java element as selection. * @param elem The initial selection of this page or null if no * selection was available */ protected void initContainerPage(IJavaElement elem) { IPackageFragmentRoot initRoot= null; if (elem != null) { initRoot= JavaModelUtil.getPackageFragmentRoot(elem); if (initRoot == null || initRoot.isArchive()) { IJavaProject jproject= elem.getJavaProject(); try { initRoot= null; IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { initRoot= roots[i]; break; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } if (initRoot == null) { initRoot= jproject.getPackageFragmentRoot(""); //$NON-NLS-1$ } } } setPackageFragmentRoot(initRoot, true); } /** * Utility method to inspect a selection to find a Java element as initial element. * @return Returns a Java element to use as initial selection, or <code>null</code>, * if none is found. */ protected IJavaElement getInitialJavaElement(IStructuredSelection selection) { IJavaElement jelem= null; if (selection != null && !selection.isEmpty()) { Object selectedElement= selection.getFirstElement(); if (selectedElement instanceof IAdaptable) { IAdaptable adaptable= (IAdaptable) selectedElement; jelem= (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (jelem == null) { IResource resource= (IResource) adaptable.getAdapter(IResource.class); if (resource != null) { IProject proj= resource.getProject(); if (proj != null) { jelem= JavaCore.create(proj); } } } } } if (jelem == null) { jelem= EditorUtility.getActiveEditorJavaInput(); } if (jelem == null) { IProject[] projects= getWorkspaceRoot().getProjects(); if (projects.length > 0) { jelem= JavaCore.create(projects[0]); } } return jelem; } /** * Creates the controls for the container field. * @param parent The parent composite * @param nColumns The number of columns to span */ protected void createContainerControls(Composite parent, int nColumns) { fContainerDialogField.doFillIntoGrid(parent, nColumns); } protected void setFocusOnContainer() { fContainerDialogField.setFocus(); } // -------- ContainerFieldAdapter -------- private class ContainerFieldAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { containerChangeControlPressed(field); } // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { containerDialogFieldChanged(field); } } private void containerChangeControlPressed(DialogField field) { // take the current jproject as init element of the dialog IPackageFragmentRoot root= getPackageFragmentRoot(); root= chooseSourceContainer(root); if (root != null) { setPackageFragmentRoot(root, true); } } private void containerDialogFieldChanged(DialogField field) { if (field == fContainerDialogField) { fContainerStatus= containerChanged(); } // tell all others handleFieldChanged(CONTAINER); } // ----------- validation ---------- /** * Called after the container field has changed. * Updates the model and returns the status. * Model is only valid if returned status is OK */ protected IStatus containerChanged() { StatusInfo status= new StatusInfo(); fCurrRoot= null; String str= getContainerText(); if ("".equals(str)) { //$NON-NLS-1$ status.setError(NewWizardMessages.getString("ContainerPage.error.EnterContainerName")); //$NON-NLS-1$ return status; } IPath path= new Path(str); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { int resType= res.getType(); if (resType == IResource.PROJECT || resType == IResource.FOLDER) { IProject proj= res.getProject(); if (!proj.isOpen()) { status.setError(NewWizardMessages.getFormattedString("ContainerPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$ return status; } IJavaProject jproject= JavaCore.create(proj); fCurrRoot= jproject.getPackageFragmentRoot(res); if (fCurrRoot.exists()) { try { if (!proj.hasNature(JavaCore.NATURE_ID)) { if (resType == IResource.PROJECT) { status.setWarning(NewWizardMessages.getString("ContainerPage.warning.NotAJavaProject")); //$NON-NLS-1$ } else { status.setWarning(NewWizardMessages.getString("ContainerPage.warning.NotInAJavaProject")); //$NON-NLS-1$ } return status; } } catch (CoreException e) { status.setWarning(NewWizardMessages.getString("ContainerPage.warning.NotAJavaProject")); //$NON-NLS-1$ } try { if (!JavaModelUtil.isOnBuildPath(jproject, fCurrRoot)) { status.setWarning(NewWizardMessages.getFormattedString("ContainerPage.warning.NotOnClassPath", str)); //$NON-NLS-1$ } } catch (JavaModelException e) { status.setWarning(NewWizardMessages.getFormattedString("ContainerPage.warning.NotOnClassPath", str)); //$NON-NLS-1$ } if (fCurrRoot.isArchive()) { status.setError(NewWizardMessages.getFormattedString("ContainerPage.error.ContainerIsBinary", str)); //$NON-NLS-1$ return status; } } return status; } else { status.setError(NewWizardMessages.getFormattedString("ContainerPage.error.NotAFolder", str)); //$NON-NLS-1$ return status; } } else { status.setError(NewWizardMessages.getFormattedString("ContainerPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$ return status; } } // -------- update message ---------------- /** * Called when a field on a page changed. Every sub type is responsible to * call this method when a field on its page has changed. * Subtypes override (extend) the method to add verification when own field has a * dependency to an other field. (for example the class name input must be verified * again, when the package field changes (check for duplicated class names)) * @param fieldName The name of the field that has changed (field id) */ protected void handleFieldChanged(String fieldName) { } // ---- get ---------------- /** * Returns the workspace root. */ public IWorkspaceRoot getWorkspaceRoot() { return fWorkspaceRoot; } /** * Returns the PackageFragmentRoot corresponding to the current input. * @return the PackageFragmentRoot or <code>null</code> if the current * input is not a valid source folder */ public IPackageFragmentRoot getPackageFragmentRoot() { return fCurrRoot; } /** * Returns the text of the container field. */ public String getContainerText() { return fContainerDialogField.getText(); } /** * Sets the current PackageFragmentRoot (model and text field). * @param canBeModified Selects if the container field can be changed by the user */ public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean canBeModified) { fCurrRoot= root; String str= (root == null) ? "" : root.getPath().makeRelative().toString(); //$NON-NLS-1$ fContainerDialogField.setText(str); fContainerDialogField.setEnabled(canBeModified); } // ------------- choose source container dialog private IPackageFragmentRoot chooseSourceContainer(IJavaElement initElement) { Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) { public boolean isSelectedValid(Object element) { try { if (element instanceof IJavaProject) { IJavaProject jproject= (IJavaProject)element; IPath path= jproject.getProject().getFullPath(); return (jproject.findPackageFragmentRoot(path) != null); } else if (element instanceof IPackageFragmentRoot) { return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); } return true; } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // just log, no ui in validation } return false; } }; acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IPackageFragmentRoot) { try { return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // just log, no ui in validation return false; } } return super.select(viewer, parent, element); } }; JavaElementContentProvider provider= new JavaElementContentProvider(); ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider); dialog.setValidator(validator); dialog.setSorter(new JavaElementSorter()); dialog.setTitle(NewWizardMessages.getString("ContainerPage.ChooseSourceContainerDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("ContainerPage.ChooseSourceContainerDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(JavaCore.create(fWorkspaceRoot)); dialog.setInitialSelection(initElement); if (dialog.open() == dialog.OK) { Object element= dialog.getFirstResult(); if (element instanceof IJavaProject) { IJavaProject jproject= (IJavaProject)element; return jproject.getPackageFragmentRoot(jproject.getProject()); } else if (element instanceof IPackageFragmentRoot) { return (IPackageFragmentRoot)element; } return null; } return null; } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewClassCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; 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.SubProgressMonitor; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewClassCreationWizardPage extends TypePage { private final static String PAGE_NAME= "NewClassCreationWizardPage"; //$NON-NLS-1$ private SelectionButtonDialogFieldGroup fMethodStubsButtons; public NewClassCreationWizardPage(IWorkspaceRoot root) { super(true, PAGE_NAME, root); setTitle(NewWizardMessages.getString("NewClassCreationWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewClassCreationWizardPage.description")); //$NON-NLS-1$ String[] buttonNames3= new String[] { NewWizardMessages.getString("NewClassCreationWizardPage.methods.main"), NewWizardMessages.getString("NewClassCreationWizardPage.methods.constructors"), //$NON-NLS-1$ //$NON-NLS-2$ NewWizardMessages.getString("NewClassCreationWizardPage.methods.inherited") //$NON-NLS-1$ }; fMethodStubsButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames3, 1); fMethodStubsButtons.setLabelText(NewWizardMessages.getString("NewClassCreationWizardPage.methods.label")); //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); updateStatus(findMostSevereStatus()); fMethodStubsButtons.setSelection(0, false); fMethodStubsButtons.setSelection(1, false); fMethodStubsButtons.setSelection(2, true); } // ------ validation -------- /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fContainerStatus, isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus, fTypeNameStatus, fModifierStatus, fSuperClassStatus, fSuperInterfacesStatus }); } /* * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); updateStatus(findMostSevereStatus()); } // ------ ui -------- /* * @see WizardPage#createControl */ public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createEnclosingTypeControls(composite, nColumns); createSeparator(composite, nColumns); createTypeNameControls(composite, nColumns); createModifierControls(composite, nColumns); // createSeparator(composite, nColumns); createSuperClassControls(composite, nColumns); createSuperInterfacesControls(composite, nColumns); //createSeparator(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setControl(composite); setFocus(); WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.NEW_CLASS_WIZARD_PAGE)); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); DialogField.createEmptySpace(composite); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } // ---- creation ---------------- /* * @see TypePage#evalMethods */ protected String[] evalMethods(IType type, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); boolean doConstr= fMethodStubsButtons.isSelected(1); boolean doInherited= fMethodStubsButtons.isSelected(2); String[] meth= constructInheritedMethods(type, doConstr, doInherited, imports, new SubProgressMonitor(monitor, 1)); for (int i= 0; i < meth.length; i++) { newMethods.add(meth[i]); } if (monitor != null) { monitor.done(); } if (fMethodStubsButtons.isSelected(0)) { String main= "public static void main(String[] args) {}"; //$NON-NLS-1$ newMethods.add(main); } return (String[]) newMethods.toArray(new String[newMethods.size()]); } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewInterfaceCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewInterfaceCreationWizardPage extends TypePage { private final static String PAGE_NAME= "NewInterfaceCreationWizardPage"; //$NON-NLS-1$ public NewInterfaceCreationWizardPage(IWorkspaceRoot root) { super(false, PAGE_NAME, root); setTitle(NewWizardMessages.getString("NewInterfaceCreationWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewInterfaceCreationWizardPage.description")); //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); updateStatus(findMostSevereStatus()); } // ------ validation -------- /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fContainerStatus, isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus, fTypeNameStatus, fModifierStatus, fSuperInterfacesStatus }); } /** * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); updateStatus(findMostSevereStatus()); } // ------ ui -------- /** * @see WizardPage#createControl */ public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createEnclosingTypeControls(composite, nColumns); createSeparator(composite, nColumns); createTypeNameControls(composite, nColumns); createModifierControls(composite, nColumns); // createSeparator(composite, nColumns); createSuperInterfacesControls(composite, nColumns); setControl(composite); setFocus(); WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.NEW_INTERFACE_WIZARD_PAGE)); } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewPackageCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaConventions; 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.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; 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.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewPackageCreationWizardPage extends ContainerPage { private static final String PAGE_NAME= "NewPackageCreationWizardPage"; //$NON-NLS-1$ protected static final String PACKAGE= "NewPackageCreationWizardPage.package"; //$NON-NLS-1$ private StringDialogField fPackageDialogField; /** * Status of last validation of the package field */ protected IStatus fPackageStatus; private IPackageFragment fCreatedPackageFragment; public NewPackageCreationWizardPage(IWorkspaceRoot root) { super(PAGE_NAME, root); setTitle(NewWizardMessages.getString("NewPackageCreationWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewPackageCreationWizardPage.description")); //$NON-NLS-1$ fCreatedPackageFragment= null; PackageFieldAdapter adapter= new PackageFieldAdapter(); fPackageDialogField= new StringDialogField(); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewPackageCreationWizardPage.package.label")); //$NON-NLS-1$ fPackageStatus= new StatusInfo(); } // -------- Initialization --------- /** * Should be called from the wizard with the input element. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); setPackageText(""); //$NON-NLS-1$ updateStatus(findMostSevereStatus()); } // -------- UI Creation --------- /** * @see WizardPage#createControl */ public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int nColumns= 3; int widthHint= SWTUtil.convertWidthInCharsToPixels(80, composite); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; layout.minimumWidth= widthHint; layout.minimumHeight= SWTUtil.convertHeightInCharsToPixels(20, composite); layout.numColumns= 3; composite.setLayout(layout); Label label= new Label(composite, SWT.WRAP); label.setText(NewWizardMessages.getString("NewPackageCreationWizardPage.info")); //$NON-NLS-1$ MGridData gd= new MGridData(); gd.widthHint= widthHint; gd.horizontalSpan= 3; label.setLayoutData(gd); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); fPackageDialogField.setFocus(); setControl(composite); WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.NEW_PACKAGE_WIZARD_PAGE)); } protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); } // -------- PackageFieldAdapter -------- private class PackageFieldAdapter implements IDialogFieldListener { // --------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { fPackageStatus= packageChanged(); // tell all others handleFieldChanged(PACKAGE); } } // -------- update message ---------------- /** * Called when a dialog field on this page changed * @see ContainerPage#fieldUpdated */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); } // do status line update updateStatus(findMostSevereStatus()); } /** * Finds the most severe error (if there is one) */ protected IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fContainerStatus, fPackageStatus); } // ----------- validation ---------- /** * Verify the input for the package field */ private IStatus packageChanged() { StatusInfo status= new StatusInfo(); String packName= fPackageDialogField.getText(); if (!"".equals(packName)) { //$NON-NLS-1$ IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewPackageCreationWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewPackageCreationWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ } } else { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.EnterName")); //$NON-NLS-1$ return status; } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getUnderlyingResource().getFullPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.IsOutputFolder")); //$NON-NLS-1$ return status; } } if (pack.exists()) { if (pack.containsJavaResources() || !pack.hasSubpackages()) { status.setError(NewWizardMessages.getString("NewPackageCreationWizardPage.error.PackageExists")); //$NON-NLS-1$ } else { status.setWarning(NewWizardMessages.getString("NewPackageCreationWizardPage.warning.PackageNotShown")); //$NON-NLS-1$ } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } return status; } protected String getPackageText() { return fPackageDialogField.getText(); } protected void setPackageText(String str) { fPackageDialogField.setText(str); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { createPackage(monitor); } catch (JavaModelException e) { throw new InvocationTargetException(e); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } public IPackageFragment getNewPackageFragment() { return fCreatedPackageFragment; } protected void createPackage(IProgressMonitor monitor) throws JavaModelException, CoreException, InterruptedException { IPackageFragmentRoot root= getPackageFragmentRoot(); String packName= getPackageText(); fCreatedPackageFragment= root.createPackageFragment(packName, true, monitor); } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewSourceFolderCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.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.jface.dialogs.IDialogConstants; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; 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.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewSourceFolderCreationWizardPage extends NewElementWizardPage { private static final String PAGE_NAME= "NewSourceFolderCreationWizardPage"; //$NON-NLS-1$ private StringButtonDialogField fProjectField; private StatusInfo fProjectStatus; private StringButtonDialogField fRootDialogField; private StatusInfo fRootStatus; private SelectionButtonDialogField fEditClassPathField; private IWorkspaceRoot fWorkspaceRoot; private IJavaProject fCurrJProject; private IClasspathEntry[] fEntries; private IPath fOutputLocation; private IPackageFragmentRoot fCreatedRoot; public NewSourceFolderCreationWizardPage(IWorkspaceRoot root) { super(PAGE_NAME); setTitle(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.description")); //$NON-NLS-1$ fWorkspaceRoot= root; RootFieldAdapter adapter= new RootFieldAdapter(); fProjectField= new StringButtonDialogField(adapter); fProjectField.setDialogFieldListener(adapter); fProjectField.setLabelText(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.project.label")); //$NON-NLS-1$ fProjectField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.project.button")); //$NON-NLS-1$ fRootDialogField= new StringButtonDialogField(adapter); fRootDialogField.setDialogFieldListener(adapter); fRootDialogField.setLabelText(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.root.label")); //$NON-NLS-1$ fRootDialogField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.root.button")); //$NON-NLS-1$ fEditClassPathField= new SelectionButtonDialogField(SWT.PUSH); fEditClassPathField.setDialogFieldListener(adapter); fEditClassPathField.setLabelText(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.editclasspath.button")); //$NON-NLS-1$ fRootStatus= new StatusInfo(); fProjectStatus= new StatusInfo(); } // -------- Initialization --------- public void init(IStructuredSelection selection) { if (selection == null || selection.isEmpty()) { setDefaultAttributes(); return; } Object selectedElement= selection.getFirstElement(); if (selectedElement == null) { selectedElement= EditorUtility.getActiveEditorJavaInput(); } String projPath= null; if (selectedElement instanceof IResource) { IProject proj= ((IResource)selectedElement).getProject(); if (proj != null) { projPath= proj.getFullPath().makeRelative().toString(); } } else if (selectedElement instanceof IJavaElement) { IJavaProject jproject= ((IJavaElement)selectedElement).getJavaProject(); if (jproject != null) { projPath= jproject.getProject().getFullPath().makeRelative().toString(); } } if (projPath != null) { fProjectField.setText(projPath); fRootDialogField.setText(""); //$NON-NLS-1$ } else { setDefaultAttributes(); } } private void setDefaultAttributes() { String projPath= ""; //$NON-NLS-1$ try { // find the first java project IProject[] projects= fWorkspaceRoot.getProjects(); for (int i= 0; i < projects.length; i++) { IProject proj= projects[i]; if (proj.hasNature(JavaCore.NATURE_ID)) { projPath= proj.getFullPath().makeRelative().toString(); break; } } } catch (CoreException e) { // ignore here } fProjectField.setText(projPath); fRootDialogField.setText(""); //$NON-NLS-1$ } // -------- UI Creation --------- /** * @see WizardPage#createControl */ public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.minimumHeight= SWTUtil.convertHeightInCharsToPixels(20, composite); layout.numColumns= 3; composite.setLayout(layout); fProjectField.doFillIntoGrid(composite, 3); fRootDialogField.doFillIntoGrid(composite, 3); fRootDialogField.setFocus(); (new Separator()).doFillIntoGrid(composite, 3); fEditClassPathField.doFillIntoGrid(composite, 3); Control control= fEditClassPathField.getSelectionButton(null); MGridData gd= (MGridData) control.getLayoutData(); gd.verticalAlignment= MGridData.END; gd.horizontalAlignment= MGridData.BEGINNING; setControl(composite); WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.NEW_PACKAGEROOT_WIZARD_PAGE)); } // -------- ContainerFieldAdapter -------- private class RootFieldAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { packRootChangeControlPressed(field); } // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { packRootDialogFieldChanged(field); } } private void packRootChangeControlPressed(DialogField field) { if (field == fRootDialogField) { IFolder folder= chooseFolder(); if (folder != null) { IPath path= folder.getFullPath().removeFirstSegments(1); fRootDialogField.setText(path.toString()); } } else if (field == fProjectField) { IJavaProject jproject= chooseProject(); if (jproject != null) { IPath path= jproject.getProject().getFullPath().makeRelative(); fProjectField.setText(path.toString()); } } } private void packRootDialogFieldChanged(DialogField field) { if (field == fRootDialogField) { updateRootStatus(); } else if (field == fProjectField) { updateProjectStatus(); updateRootStatus(); } else if (field == fEditClassPathField) { if (showClassPathPropertyPage()) { updateProjectStatus(); updateRootStatus(); } } updateStatus(findMostSevereStatus()); } private void updateProjectStatus() { fCurrJProject= null; String str= fProjectField.getText(); if ("".equals(str)) { //$NON-NLS-1$ fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.error.EnterProjectName")); //$NON-NLS-1$ return; } IPath path= new Path(str); if (path.segmentCount() != 1) { fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.error.InvalidProjectPath")); //$NON-NLS-1$ return; } IProject project= fWorkspaceRoot.getProject(path.toString()); if (!project.exists()) { fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.error.ProjectNotExists")); //$NON-NLS-1$ return; } try { if (project.hasNature(JavaCore.NATURE_ID)) { fCurrJProject= JavaCore.create(project); fEntries= fCurrJProject.getRawClasspath(); fOutputLocation= fCurrJProject.getOutputLocation(); fProjectStatus.setOK(); return; } } catch (CoreException e) { JavaPlugin.log(e); fCurrJProject= null; } fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.error.NotAJavaProject")); //$NON-NLS-1$ } private void updateRootStatus() { fRootDialogField.enableButton(fCurrJProject != null); if (fCurrJProject == null) { return; } String str= fRootDialogField.getText(); if (str.length() == 0) { fRootStatus.setError(NewWizardMessages.getFormattedString("NewSourceFolderCreationWizardPage.error.EnterRootName", fCurrJProject.getProject().getFullPath().toString())); //$NON-NLS-1$ } else { IPath path= fCurrJProject.getProject().getFullPath().append(str); if (!fWorkspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) { fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.error.InvalidRootName")); //$NON-NLS-1$ } else { IResource res= fWorkspaceRoot.findMember(path); if (res != null) { if (res.getType() != IResource.FOLDER) { fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.error.NotAFolder")); //$NON-NLS-1$ return; } } IClasspathEntry[] newEntries= new IClasspathEntry[fEntries.length + 1]; for (int i= 0; i < fEntries.length; i++) { IClasspathEntry curr= fEntries[i]; if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (path.equals(curr.getPath())) { fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.error.AlreadyExisting")); //$NON-NLS-1$ return; } } newEntries[i]= curr; } newEntries[fEntries.length]= JavaCore.newSourceEntry(path); IStatus status= JavaConventions.validateClasspath(fCurrJProject, newEntries, fOutputLocation); if (!status.isOK()) { fRootStatus.setError(status.getMessage()); return; } fRootStatus.setOK(); } } } protected IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fProjectStatus, fRootStatus); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { fCreatedRoot= createPackageFragmentRoot(monitor, getShell()); } catch (JavaModelException e) { throw new InvocationTargetException(e); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } protected IPackageFragmentRoot getNewPackageFragmentRoot() { return fCreatedRoot; } protected IPackageFragmentRoot createPackageFragmentRoot(IProgressMonitor monitor, Shell shell) throws CoreException, JavaModelException { String relPath= fRootDialogField.getText(); IFolder folder= fCurrJProject.getProject().getFolder(relPath); IPath path= folder.getFullPath(); if (!folder.exists()) { CoreUtility.createFolder(folder, true, true, monitor); } IClasspathEntry[] entries= fCurrJProject.getRawClasspath(); int nEntries= entries.length; IClasspathEntry[] newEntries= new IClasspathEntry[nEntries + 1]; for (int i= 0; i < nEntries; i++) { newEntries[i]= entries[i]; } newEntries[nEntries]= JavaCore.newSourceEntry(path); fCurrJProject.setRawClasspath(newEntries, monitor); return fCurrJProject.getPackageFragmentRoot(folder); } // ------------- choose dialogs private IFolder chooseFolder() { Class[] acceptedClasses= new Class[] { IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); Object[] notWanted= getFilteredExistingContainerEntries(); ViewerFilter filter= new TypedViewerFilter(acceptedClasses, notWanted); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.ChooseExistingRootDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.ChooseExistingRootDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fCurrJProject.getProject()); IResource res= fWorkspaceRoot.findMember(new Path(fRootDialogField.getText())); if (res != null) { dialog.setInitialSelection(res); } if (dialog.open() == dialog.OK) { return (IFolder) dialog.getFirstResult(); } return null; } private IJavaProject chooseProject() { IJavaProject[] projects; try { projects= JavaCore.create(fWorkspaceRoot).getJavaProjects(); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); projects= new IJavaProject[0]; } ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider); dialog.setTitle(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.ChooseProjectDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.ChooseProjectDialog.description")); //$NON-NLS-1$ dialog.setElements(projects); dialog.setInitialSelections(new Object[] { fCurrJProject }); if (dialog.open() == dialog.OK) { return (IJavaProject) dialog.getFirstResult(); } return null; } // a dialog containing the class path dialog private class EditClassPathDialog extends StatusDialog implements IStatusChangeListener { private BuildPathsBlock fBuildPathsBlock; public EditClassPathDialog(Shell parent) { super(parent); fBuildPathsBlock= new BuildPathsBlock(fWorkspaceRoot, this, false); } public void create() { super.create(); fBuildPathsBlock.init(fCurrJProject, null, null); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Control inner= fBuildPathsBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } public void statusChanged(IStatus status) { updateStatus(status); } protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.OK_ID) { IRunnableWithProgress runnable= fBuildPathsBlock.getRunnable(); if (invokeRunnable(runnable)) { setReturnCode(OK); } else { setReturnCode(CANCEL); } } close(); } private boolean invokeRunnable(IRunnableWithProgress runnable) { IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable); try { getWizard().getContainer().run(false, true, op); } catch (InvocationTargetException e) { Shell shell= getShell(); String title= NewWizardMessages.getString("NewSourceFolderCreationWizardPage.op_error.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("NewSourceFolderCreationWizardPage.op_error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, shell, title, message); return false; } catch (InterruptedException e) { return false; } return true; } } private boolean showClassPathPropertyPage() { EditClassPathDialog dialog= new EditClassPathDialog(getShell()); dialog.setTitle(NewWizardMessages.getString("NewSourceFolderCreationWizardPage.EditClassPathDialog.title")); //$NON-NLS-1$ return (dialog.open() == EditClassPathDialog.OK); } private IContainer[] getFilteredExistingContainerEntries() { if (fCurrJProject == null) { return new IContainer[0]; } List res= new ArrayList(); try { IResource container= fWorkspaceRoot.findMember(fCurrJProject.getOutputLocation()); if (container != null) { res.add(container); } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } for (int i= 0; i < fEntries.length; i++) { IClasspathEntry elem= fEntries[i]; if (elem.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IResource container= fWorkspaceRoot.findMember(elem.getPath()); if (container != null) { res.add(container); } } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/TypePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.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.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.compiler.env.IConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.ui.codemanipulation.StubUtility; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; /** * <code>TypePage</code> contains controls and validation routines for a 'New Type WizardPage' * Implementors decide which components to add and to enable. Implementors can also * customize the validation code. * <code>TypePage</code> is intended to serve as base class of all wizards that create types. * Applets, Servlets, Classes, Interfaces... * See <code>NewClassCreationWizardPage</code> or <code>NewInterfaceCreationWizardPage</code> for an * example usage of TypePage. */ public abstract class TypePage extends ContainerPage { private final static String PAGE_NAME= "TypePage"; //$NON-NLS-1$ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPlugin.getDefault().getImageRegistry().get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; public TypePage(boolean isClass, String pageName, IWorkspaceRoot root) { super(pageName, root); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("TypePage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("TypePage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("TypePage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("TypePage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("TypePage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("TypePage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("TypePage.interfaces.class.label") : NewWizardMessages.getString("TypePage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("TypePage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("TypePage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("TypePage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("TypePage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("TypePage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the type page with a given * Java element as selection. * @param elem The initial selection of this page or null if no * selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= JavaModelUtil.findPrimaryType(cu); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { initializeDialogUnits(composite); (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, 4); } /** * Creates the controls for the enclosing type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { fEnclosingTypeSelection.doFillIntoGrid(composite, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); c.setLayoutData(new MGridData(MGridData.FILL_HORIZONTAL)); LayoutUtil.setHorizontalSpan(c, 2); c= fEnclosingTypeDialogField.getChangeControl(composite); c.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); } /** * Creates the controls for the type name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); } /** * Creates the controls for the modifiers radio/ceckbox buttons. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); Control control= fAccMdfButtons.getSelectionButtonsGroup(composite); MGridData gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); control= fOtherMdfButtons.getSelectionButtonsGroup(composite); gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); } /** * Creates the controls for the superclass name field. * @param composite The parent composite * @param nColumns Number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { initializeDialogUnits(composite); fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); MGridData gd= (MGridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; } /** * Sets the focus on the container if empty, elso on type name. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /** * Called whenever a content of a field has changed. * Implementors of TypePage can hook in. * @see ContainerPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Gets the text of package field. */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Gets the text of enclosing type field. */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * @return Returns <code>null</code> if the input could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the package fragment can be changed by the user */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the encloding type corresponding to the current input. * @return Returns <code>null</code> if enclosing type is not selected or the input could not * be resolved. */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the package fragment. * This will update model and the text of the control. * @param canBeModified Selects if the enclosing type can be changed by the user */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns <code>true</code> if the enclosing type selection check box is enabled. */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type selection checkbox. * @param canBeModified Selects if the enclosing type selection can be changed by the user */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Gets the type name. */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name. * @param canBeModified Selects if the type name can be changed by the user */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Gets the selected modifiers. * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= IConstants.AccPublic; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= IConstants.AccPrivate; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= IConstants.AccProtected; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= IConstants.AccAbstract; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= IConstants.AccFinal; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= IConstants.AccStatic; } return mdf; } /** * Sets the modifiers. * @param canBeModified Selects if the modifiers can be changed by the user * @see IConstants */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Gets the content of the super class text field. */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * @param canBeModified Selects if the super class can be changed by the user */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Gets the currently chosen super interfaces. * @return returns a list of String */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * @param interfacesNames a list of String */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * Called when the package field has changed. * The method validates the package name and returns the status of the validation * This also updates the package fragment model. * Can be extended to add more validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getUnderlyingResource().getFullPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("TypePage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass } fCurrPackage= pack; } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= fPackageDialogField.getText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Called when the enclosing type name has changed. * The method validates the enclosing type and returns the status of the validation * This also updates the enclosing type model. * Can be extended to add more validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= JavaModelUtil.findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); return status; } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("TypePage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("TypePage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Called when the superclass name has changed. * The method validates the superclass name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (!val.isOK()) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("TypePage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e.getStatus()); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= JavaModelUtil.findType(jproject, packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= JavaModelUtil.findType(jproject, sclassName); } } return type; } /** * Called when the list of super interface has changed. * The method validates the superinterfaces and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= JavaModelUtil.findType(root.getJavaProject(), intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass, checking is an extra } } } return status; } /** * Called when the modifiers have changed. * The method validates the modifiers and returns the status of the validation. * Can be extended to add more validation. */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("TypePage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null) { packages= froot.getChildren(); } } catch (JavaModelException e) { } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("TypePage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); if (fCurrPackage != null) { dialog.setInitialSelections(new Object[] { fCurrPackage }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_TYPES); dialog.setTitle(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ if (fCurrEnclosingType != null) { dialog.setInitialSelections(new Object[] { fCurrEnclosingType }); dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1)); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES); dialog.setTitle(NewWizardMessages.getString("TypePage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.SuperClassDialog.message")); //$NON-NLS-1$ if (fSuperClass != null) { dialog.setFilter(fSuperClass.getElementName()); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(NewWizardMessages.getString("TypePage.InterfacesDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("TypePage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates a type using the current field values. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("TypePage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= fTypeNameDialogField.getText(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); lineDelimiter= StubUtility.getLineDelimiterUsed(parentCU); String content= createTypeBody(imports, lineDelimiter); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); String content= createTypeBody(imports, lineDelimiter); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so the type can be parsed correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1)); if (methods.length > 0) { for (int i= 0; i < methods.length; i++) { createdType.createMethod(methods[i], null, false, null); } // add imports imports.create(!isInnerClass, null); } monitor.worked(1); String formattedContent= StubUtility.codeFormat(createdType.getSource(), indent, lineDelimiter); ISourceRange range= createdType.getSourceRange(); IBuffer buf= createdType.getCompilationUnit().getBuffer(); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. Only valid after createType has been invoked */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, IImportsStructure imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ buf.append(Signature.getSimpleName(typename)); if (fSuperClass != null) { imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass)); } else { imports.addImport(typename); } } } private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); imports.addImport(typename); buf.append(Signature.getSimpleName(typename)); if (i < last) { buf.append(", "); //$NON-NLS-1$ } } } } /* * Called from createType to construct the source for this type */ private String createTypeBody(IImportsStructure imports, String lineDelimiter) { StringBuffer buf= new StringBuffer(); int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append(" {"); //$NON-NLS-1$ buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * Called from createType to allow adding methods for the newly created type * Returns array of sources of the methods that have to be added * @param parent The type where the methods will be added to */ protected String[] evalMethods(IType parent, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return new String[0]; } /** * Creates the bodies of all unimplemented methods or/and all constructors * Can be used by implementors of TypePage to add method stub checkboxes */ protected String[] constructInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { List newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { StubUtility.evalConstructors(type, superclass, newMethods, imports); } } if (doUnimplementedMethods) { StubUtility.evalUnimplementedMethods(type, hierarchy, false, newMethods, imports); } return (String[]) newMethods.toArray(new String[newMethods.size()]); } // ---- creation ---------------- /** * @see NewElementWizardPage#getRunnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class BuildPathsBlock { private IWorkspaceRoot fWorkspaceRoot; private CheckedListDialogField fClassPathList; private StringDialogField fBuildPathDialogField; private StatusInfo fClassPathStatus; private StatusInfo fBuildPathStatus; private IJavaProject fCurrJProject; private IPath fOutputLocationPath; private IStatusChangeListener fContext; private Control fSWTWidget; private boolean fIsNewProject; private SourceContainerWorkbookPage fSourceContainerPage; private ProjectsWorkbookPage fProjectsPage; private LibrariesWorkbookPage fLibrariesPage; private BuildPathBasePage fCurrPage; public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean isNewProject) { fWorkspaceRoot= root; fContext= context; fIsNewProject= isNewProject; fSourceContainerPage= null; fLibrariesPage= null; fProjectsPage= null; fCurrPage= null; BuildPathAdapter adapter= new BuildPathAdapter(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$ }; fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fClassPathList.setDialogFieldListener(adapter); fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); fClassPathList.setUpButtonIndex(0); fClassPathList.setDownButtonIndex(1); fClassPathList.setCheckAllButtonIndex(3); fClassPathList.setUncheckAllButtonIndex(4); if (isNewProject) { fBuildPathDialogField= new StringDialogField(); } else { StringButtonDialogField dialogField= new StringButtonDialogField(adapter); dialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$ fBuildPathDialogField= dialogField; } fBuildPathDialogField.setDialogFieldListener(adapter); fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$ fBuildPathStatus= new StatusInfo(); fClassPathStatus= new StatusInfo(); fCurrJProject= null; } // -------- UI creation --------- public Control createControl(Composite parent) { fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.minimumHeight= SWTUtil.convertHeightInCharsToPixels(20, composite); layout.numColumns= 1; composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new MGridData(MGridData.FILL_BOTH)); folder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabChanged(e.item); } }); ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry(); TabItem item; fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField, fIsNewProject); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT)); item.setData(fSourceContainerPage); item.setControl(fSourceContainerPage.getControl(folder)); IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); fProjectsPage= new ProjectsWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$ item.setImage(projectImage); item.setData(fProjectsPage); item.setControl(fProjectsPage.getControl(folder)); fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY)); item.setData(fLibrariesPage); item.setControl(fLibrariesPage.getControl(folder)); // a non shared image Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage(); composite.addDisposeListener(new ImageDisposer(cpoImage)); ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$ item.setImage(cpoImage); item.setData(ordpage); item.setControl(ordpage.getControl(folder)); if (fCurrJProject != null) { fSourceContainerPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); } Composite editorcomp= new Composite(composite, SWT.NONE); DialogField[] editors= new DialogField[] { fBuildPathDialogField }; LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0, 0, 0); editorcomp.setLayoutData(new MGridData(MGridData.FILL_HORIZONTAL)); if (fIsNewProject) { folder.setSelection(0); fCurrPage= fSourceContainerPage; } else { folder.setSelection(3); fCurrPage= ordpage; } WorkbenchHelp.setHelp(composite, new Object[] { IJavaHelpContextIds.BUILD_PATH_BLOCK }); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Initializes the classpath for the given project. Multiple calls to init are allowed, * but all existing settings will be cleared and replace by the given or default paths. * @param project The java project to configure. Does not have to exist. * @param outputLocation The output location to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * output location of the existing project * @param classpathEntries The classpath entries to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * classpath entries of the existing project */ public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) { fCurrJProject= jproject; boolean projExists= false; try { IProject project= fCurrJProject.getProject(); projExists= (project.exists() && project.hasNature(JavaCore.NATURE_ID)); if (projExists) { if (outputLocation == null) { outputLocation= fCurrJProject.getOutputLocation(); } if (classpathEntries == null) { classpathEntries= fCurrJProject.getRawClasspath(); } } } catch (CoreException e) { JavaPlugin.log(e.getStatus()); } if (outputLocation == null) { outputLocation= getDefaultBuildPath(jproject); } List newClassPath; if (classpathEntries == null) { newClassPath= getDefaultClassPath(jproject); } else { newClassPath= new ArrayList(); for (int i= 0; i < classpathEntries.length; i++) { IClasspathEntry curr= classpathEntries[i]; int entryKind= curr.getEntryKind(); IPath path= curr.getPath(); boolean isExported= curr.isExported(); // get the resource IResource res= null; boolean isMissing= false; if (entryKind != IClasspathEntry.CPE_VARIABLE) { res= fWorkspaceRoot.findMember(path); if (res == null) { isMissing= (entryKind != IClasspathEntry.CPE_LIBRARY || !path.toFile().isFile()); } } else { IPath resolvedPath= JavaCore.getResolvedVariablePath(path); isMissing= (resolvedPath == null) || !resolvedPath.toFile().isFile(); } CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported); if (projExists) { elem.setIsMissing(isMissing); } newClassPath.add(elem); } } List exportedEntries = new ArrayList(); for (int i= 0; i < newClassPath.size(); i++) { CPListElement curr= (CPListElement) newClassPath.get(i); if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { exportedEntries.add(curr); } } // inits the dialog field fBuildPathDialogField.setText(outputLocation.makeRelative().toString()); fClassPathList.setElements(newClassPath); fClassPathList.setCheckedElements(exportedEntries); if (fSourceContainerPage != null) { fSourceContainerPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); } doStatusLineUpdate(); } // -------- public api -------- /** * Returns the Java project. Can return <code>null<code> if the page has not * been initialized. */ public IJavaProject getJavaProject() { return fCurrJProject; } /** * Returns the current output location. Note that the path returned must not be valid. */ public IPath getOutputLocation() { return new Path(fBuildPathDialogField.getText()).makeAbsolute(); } /** * Returns the current class path (raw). Note that the entries returned must not be valid. */ public IClasspathEntry[] getRawClassPath() { List elements= fClassPathList.getElements(); int nElements= elements.size(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= 0; i < nElements; i++) { CPListElement currElement= (CPListElement) elements.get(i); entries[i]= currElement.getClasspathEntry(); } return entries; } // -------- evaluate default settings -------- private List getDefaultClassPath(IJavaProject jproj) { List list= new ArrayList(); IResource srcFolder; if (JavaBasePreferencePage.useSrcAndBinFolders()) { srcFolder= jproj.getProject().getFolder("src"); //$NON-NLS-1$ } else { srcFolder= jproj.getProject(); } list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder)); IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE); IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE); IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE); CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false); list.add(elem); return list; } private IPath getDefaultBuildPath(IJavaProject jproj) { if (JavaBasePreferencePage.useSrcAndBinFolders()) { return jproj.getProject().getFullPath().append("bin"); //$NON-NLS-1$ } else { return jproj.getProject().getFullPath(); } } private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { buildPathChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { buildPathDialogFieldChanged(field); } } private void buildPathChangeControlPressed(DialogField field) { if (field == fBuildPathDialogField) { IContainer container= chooseContainer(); if (container != null) { fBuildPathDialogField.setText(container.getFullPath().toString()); } } } private void buildPathDialogFieldChanged(DialogField field) { if (field == fClassPathList) { updateClassPathStatus(); updateBuildPathStatus(); } else if (field == fBuildPathDialogField) { updateBuildPathStatus(); } doStatusLineUpdate(); } // -------- verification ------------------------------- private void doStatusLineUpdate() { IStatus res= findMostSevereStatus(); fContext.statusChanged(res); } private IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus); } /** * Validates the build path. */ private void updateClassPathStatus() { fClassPathStatus.setOK(); List elements= fClassPathList.getElements(); boolean entryMissing= false; IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); boolean isChecked= fClassPathList.isChecked(currElement); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!isChecked) { fClassPathList.setCheckedWithoutUpdate(currElement, true); } } else { currElement.setExported(isChecked); } entries[i]= currElement.getClasspathEntry(); entryMissing= entryMissing || currElement.isMissing(); } if (entryMissing) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$ } if (fCurrJProject.hasClasspathCycle(entries)) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$ } } /** * Validates output location & build path. */ private void updateBuildPathStatus() { fOutputLocationPath= null; String text= fBuildPathDialogField.getText(); if ("".equals(text)) { //$NON-NLS-1$ fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$ return; } IPath path= getOutputLocation(); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { // if exists, must be a folder or project if (res.getType() == IResource.FILE) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$ return; } } else { // allows the build path to be in a different project, but must exists and be open IPath projPath= path.uptoSegment(1); if (!projPath.equals(fCurrJProject.getProject().getFullPath())) { IProject proj= (IProject)fWorkspaceRoot.findMember(projPath); if (proj == null || !proj.isOpen()) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.BuildPathProjNotExists")); //$NON-NLS-1$ return; } } } fOutputLocationPath= path; List elements= fClassPathList.getElements(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); entries[i]= currElement.getClasspathEntry(); } IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path); if (!status.isOK()) { fBuildPathStatus.setError(status.getMessage()); return; } fBuildPathStatus.setOK(); } // -------- creation ------------------------------- /** * Creates a runnable that sets the configured build paths. */ public IRunnableWithProgress getRunnable() { final List classPathEntries= fClassPathList.getElements(); final IPath path= getOutputLocation(); return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 12); //$NON-NLS-1$ try { createJavaProject(classPathEntries, path, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; } /** * Creates the Java project and sets the configured build path and output location. * If the project already exists only build paths are updated. */ private void createJavaProject(List classPathEntries, IPath buildPath, IProgressMonitor monitor) throws CoreException { IProject project= fCurrJProject.getProject(); if (!project.exists()) { project.create(null); } if (!project.isOpen()) { project.open(null); } // create java nature if (!project.hasNature(JavaCore.NATURE_ID)) { addNatureToProject(project, JavaCore.NATURE_ID, null); } monitor.worked(1); String[] prevRequiredProjects= fCurrJProject.getRequiredProjectNames(); // create and set the output path first if (!fWorkspaceRoot.exists(buildPath)) { IFolder folder= fWorkspaceRoot.getFolder(buildPath); CoreUtility.createFolder(folder, true, true, null); } monitor.worked(1); fCurrJProject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 3)); int nEntries= classPathEntries.size(); IClasspathEntry[] classpath= new IClasspathEntry[nEntries]; // create and set the class path for (int i= 0; i < nEntries; i++) { CPListElement entry= ((CPListElement)classPathEntries.get(i)); IResource res= entry.getResource(); if ((res instanceof IFolder) && !res.exists()) { CoreUtility.createFolder((IFolder)res, true, true, null); } classpath[i]= entry.getClasspathEntry(); } monitor.worked(1); fCurrJProject.setRawClasspath(classpath, new SubProgressMonitor(monitor, 5)); } /** * Adds a nature to a project */ private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException { IProjectDescription description = proj.getDescription(); String[] prevNatures= description.getNatureIds(); String[] newNatures= new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length]= natureId; description.setNatureIds(newNatures); proj.setDescription(description, monitor); } // ---------- util method ------------ private IContainer chooseContainer() { Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); IProject[] allProjects= fWorkspaceRoot.getProjects(); ArrayList rejectedElements= new ArrayList(allProjects.length); IProject currProject= fCurrJProject.getProject(); for (int i= 0; i < allProjects.length; i++) { if (!allProjects[i].equals(currProject)) { rejectedElements.add(allProjects[i]); } } ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSelection= null; if (fOutputLocationPath != null) { initSelection= fWorkspaceRoot.findMember(fOutputLocationPath); } ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$ dialog.setValidator(validator); dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSelection); if (dialog.open() == dialog.OK) { return (IContainer)dialog.getFirstResult(); } return null; } // -------- tab switching ---------- private void tabChanged(Widget widget) { if (widget instanceof TabItem) { BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData(); if (fCurrPage != null) { List selection= fCurrPage.getSelection(); if (!selection.isEmpty()) { newPage.setSelection(selection); } } fCurrPage= newPage; } } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/ClasspathOrderingWorkbookPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class ClasspathOrderingWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; public ClasspathOrderingWorkbookPage(ListDialogField classPathList) { fClassPathList= classPathList; } public Control getControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); DialogField[] editors= new DialogField[] { fClassPathList }; LayoutUtil.doDefaultLayout(composite, editors, true, 0, 0, SWT.DEFAULT, SWT.DEFAULT); int buttonBarWidth= SWTUtil.convertWidthInCharsToPixels(24, composite); fClassPathList.setButtonsMinWidth(buttonBarWidth); return composite; } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { return fClassPathList.getSelectedElements(); } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { fClassPathList.selectElements(new StructuredSelection(selElements)); } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.IUIConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class LibrariesWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; private IJavaProject fCurrJProject; private ListDialogField fLibrariesList; private IWorkspaceRoot fWorkspaceRoot; private IDialogSettings fDialogSettings; private Control fSWTControl; public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) { fClassPathList= classPathList; fWorkspaceRoot= root; fSWTControl= null; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addnew.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addexisting.button"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$ /* 3 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$ /* 5 */ null, /* 6 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.setsource.button"), //$NON-NLS-1$ /* 7 */ null, /* 8 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.remove.button") //$NON-NLS-1$ }; LibrariesAdapter adapter= new LibrariesAdapter(); fLibrariesList= new ListDialogField(adapter, buttonLabels, new CPListLabelProvider()); fLibrariesList.setDialogFieldListener(adapter); fLibrariesList.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.libraries.label")); //$NON-NLS-1$ fLibrariesList.setRemoveButtonIndex(8); //$NON-NLS-1$ fLibrariesList.enableButton(6, false); } public void init(IJavaProject jproject) { fCurrJProject= jproject; updateLibrariesList(); } private void updateLibrariesList() { List cpelements= fClassPathList.getElements(); List libelements= new ArrayList(cpelements.size()); int nElements= cpelements.size(); for (int i= 0; i < nElements; i++) { CPListElement cpe= (CPListElement)cpelements.get(i); int kind= cpe.getEntryKind(); if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) { libelements.add(cpe); } } fLibrariesList.setElements(libelements); } // -------- ui creation public Control getControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true, 0, 0, SWT.DEFAULT, SWT.DEFAULT); int buttonBarWidth= SWTUtil.convertWidthInCharsToPixels(24, composite); fLibrariesList.setButtonsMinWidth(buttonBarWidth); fLibrariesList.getTableViewer().setSorter(new CPListElementSorter()); fSWTControl= composite; return composite; } private Shell getShell() { if (fSWTControl != null) { return fSWTControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private class LibrariesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { libaryPageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) { libaryPageSelectionChanged(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { libaryPageDialogFieldChanged(field); } } private void libaryPageCustomButtonPressed(DialogField field, int index) { CPListElement[] libentries= null; switch (index) { case 0: /* add new */ libentries= createNewClassContainer(); break; case 1: /* add existing */ libentries= chooseClassContainers(); break; case 2: /* add jar */ libentries= chooseJarFiles(); break; case 3: /* add external jar */ libentries= chooseExtJarFiles(); break; case 4: /* add variable */ libentries= chooseVariableEntries(); break; case 6: /* set source attachment */ List selElements= fLibrariesList.getSelectedElements(); CPListElement selElement= (CPListElement) selElements.get(0); SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), selElement.getClasspathEntry()); if (dialog.open() == dialog.OK) { selElement.setSourceAttachment(dialog.getSourceAttachmentPath(), dialog.getSourceAttachmentRootPath()); fLibrariesList.refresh(); fClassPathList.refresh(); } break; } if (libentries != null) { int nElementsChosen= libentries.length; // remove duplicates List cplist= fLibrariesList.getElements(); List elementsToAdd= new ArrayList(nElementsChosen); for (int i= 0; i < nElementsChosen; i++) { CPListElement curr= libentries[i]; if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) { elementsToAdd.add(curr); addAttachmentsFromExistingLibs(curr); } } fLibrariesList.addElements(elementsToAdd); fLibrariesList.postSetSelection(new StructuredSelection(libentries)); } } private void libaryPageSelectionChanged(DialogField field) { List selElements= fLibrariesList.getSelectedElements(); fLibrariesList.enableButton(6, canDoSourceAttachment(selElements)); } private void libaryPageDialogFieldChanged(DialogField field) { if (fCurrJProject != null) { // already initialized updateClasspathList(); } } private boolean canDoSourceAttachment(List selElements) { if (selElements != null && selElements.size() == 1) { CPListElement elem= (CPListElement) selElements.get(0); return (!(elem.getResource() instanceof IFolder)); } return false; } private void updateClasspathList() { List projelements= fLibrariesList.getElements(); boolean remove= false; List cpelements= fClassPathList.getElements(); // backwards, as entries will be deleted for (int i= cpelements.size() - 1; i >= 0; i--) { CPListElement cpe= (CPListElement)cpelements.get(i); int kind= cpe.getEntryKind(); if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) { if (!projelements.remove(cpe)) { cpelements.remove(i); remove= true; } } } for (int i= 0; i < projelements.size(); i++) { cpelements.add(projelements.get(i)); } if (remove || (projelements.size() > 0)) { fClassPathList.setElements(cpelements); } } private CPListElement[] createNewClassContainer() { String title= NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.title"); //$NON-NLS-1$ IProject currProject= fCurrJProject.getProject(); NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers()); IPath projpath= currProject.getFullPath(); dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$ int ret= dialog.open(); if (ret == dialog.OK) { IFolder folder= dialog.getFolder(); return new CPListElement[] { newCPLibraryElement(folder) }; } return null; } private CPListElement[] chooseClassContainers() { Class[] acceptedClasses= new Class[] { IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); acceptedClasses= new Class[] { IProject.class, IFolder.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource) elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private CPListElement[] chooseJarFiles() { Class[] acceptedClasses= new Class[] { IFile.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource)elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private IContainer[] getUsedContainers() { ArrayList res= new ArrayList(); if (fCurrJProject.exists()) { try { IPath outputLocation= fCurrJProject.getOutputLocation(); if (outputLocation != null) { IResource resource= fWorkspaceRoot.findMember(outputLocation); if (resource instanceof IContainer) { res.add(resource); } } } catch (JavaModelException e) { // ignore it here, just log JavaPlugin.log(e.getStatus()); } } List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IContainer) { res.add(resource); } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } private IFile[] getUsedJARFiles() { List res= new ArrayList(); List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IFile) { res.add(resource); } } return (IFile[]) res.toArray(new IFile[res.size()]); } private CPListElement newCPLibraryElement(IResource res) { return new CPListElement(IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res); }; private CPListElement[] chooseExtJarFiles() { String lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR); if (lastUsedPath == null) { lastUsedPath= ""; //$NON-NLS-1$ } FileDialog dialog= new FileDialog(getShell(), SWT.MULTI); dialog.setText(NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(lastUsedPath); String res= dialog.open(); if (res == null) { return null; } String[] fileNames= dialog.getFileNames(); int nChosen= fileNames.length; IPath filterPath= new Path(dialog.getFilterPath()); CPListElement[] elems= new CPListElement[nChosen]; for (int i= 0; i < nChosen; i++) { IPath path= filterPath.append(fileNames[i]).makeAbsolute(); elems[i]= new CPListElement(IClasspathEntry.CPE_LIBRARY, path, null); } fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString()); return elems; } private CPListElement[] chooseVariableEntries() { ArrayList existingPaths= new ArrayList(); for (int i= 0; i < fLibrariesList.getSize(); i++) { CPListElement elem= (CPListElement) fLibrariesList.getElement(i); if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { existingPaths.add(elem.getPath()); } } VariableSelectionDialog dialog= new VariableSelectionDialog(getShell(), existingPaths); if (dialog.open() == dialog.OK) { IPath path= dialog.getVariable(); CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, path, null); IPath resolvedPath= JavaCore.getResolvedVariablePath(path); elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().isFile()); return new CPListElement[] { elem }; } return null; } private void addAttachmentsFromExistingLibs(CPListElement elem) { try { IJavaModel jmodel= fCurrJProject.getJavaModel(); IJavaProject[] jprojects= jmodel.getJavaProjects(); for (int i= 0; i < jprojects.length; i++) { IJavaProject curr= jprojects[i]; if (!curr.equals(fCurrJProject)) { IClasspathEntry[] entries= curr.getRawClasspath(); for (int k= 0; k < entries.length; k++) { IClasspathEntry entry= entries[k]; if (entry.getEntryKind() == elem.getEntryKind() && entry.getPath().equals(elem.getPath())) { IPath attachPath= entry.getSourceAttachmentPath(); if (attachPath != null && !attachPath.isEmpty()) { elem.setSourceAttachment(attachPath, entry.getSourceAttachmentRootPath()); return; } } } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } // a dialog to set the source attachment properties private class VariableSelectionDialog extends StatusDialog implements IStatusChangeListener { private VariableSelectionBlock fVariableSelectionBlock; public VariableSelectionDialog(Shell parent, List existingPaths) { super(parent); setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.title")); //$NON-NLS-1$ String initVar= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTVARIABLE); fVariableSelectionBlock= new VariableSelectionBlock(this, existingPaths, null, initVar, false); } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, new Object[] { IJavaHelpContextIds.VARIABLE_SELECTION_DIALOG }); } /* * @see StatusDialog#createDialogArea() */ protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Label message= new Label(composite, SWT.WRAP); message.setText(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.message")); //$NON-NLS-1$ message.setLayoutData(new GridData()); Control inner= fVariableSelectionBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } /* * @see Dialog#okPressed() */ protected void okPressed() { fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTVARIABLE, getVariable().segment(0)); super.okPressed(); } /* * @see IStatusChangeListener#statusChanged() */ public void statusChanged(IStatus status) { updateStatus(status); } public IPath getVariable() { return fVariableSelectionBlock.getVariablePath(); } } // a dialog to set the source attachment properties private class SourceAttachmentDialog extends StatusDialog implements IStatusChangeListener { private SourceAttachmentBlock fSourceAttachmentBlock; public SourceAttachmentDialog(Shell parent, IClasspathEntry entry) { super(parent); setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.SourceAttachmentDialog.title", entry.getPath().toString())); //$NON-NLS-1$ fSourceAttachmentBlock= new SourceAttachmentBlock(fWorkspaceRoot, this, entry); } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, new Object[] { IJavaHelpContextIds.SOURCE_ATTACHMENT_DIALOG }); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Control inner= fSourceAttachmentBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } public void statusChanged(IStatus status) { updateStatus(status); } public IPath getSourceAttachmentPath() { return fSourceAttachmentBlock.getSourceAttachmentPath(); } public IPath getSourceAttachmentRootPath() { return fSourceAttachmentBlock.getSourceAttachmentRootPath(); } } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { return fLibrariesList.getSelectedElements(); } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { for (int i= selElements.size()-1; i >= 0; i--) { CPListElement curr= (CPListElement) selElements.get(i); int kind= curr.getEntryKind(); if (kind != IClasspathEntry.CPE_LIBRARY && kind != IClasspathEntry.CPE_VARIABLE) { selElements.remove(i); } } fLibrariesList.selectElements(new StructuredSelection(selElements)); } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/NewContainerDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; 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.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class NewContainerDialog extends StatusDialog { private StringDialogField fContainerDialogField; private StatusInfo fContainerFieldStatus; private IFolder fFolder; private IContainer[] fExistingFolders; private IProject fCurrProject; public NewContainerDialog(Shell parent, String title, IProject project, IContainer[] existingFolders) { super(parent); setTitle(title); fContainerFieldStatus= new StatusInfo(); SourceContainerAdapter adapter= new SourceContainerAdapter(); fContainerDialogField= new StringDialogField(); fContainerDialogField.setDialogFieldListener(adapter); fFolder= null; fExistingFolders= existingFolders; fCurrProject= project; fContainerDialogField.setText(""); //$NON-NLS-1$ } public void setMessage(String message) { fContainerDialogField.setLabelText(message); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.minimumWidth= convertWidthInCharsToPixels(70); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 1; inner.setLayout(layout); fContainerDialogField.doFillIntoGrid(inner, 2); fContainerDialogField.postSetFocusOnDialogField(parent.getDisplay()); return composite; } // -------- SourceContainerAdapter -------- private class SourceContainerAdapter implements IDialogFieldListener { // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { doStatusLineUpdate(); } } protected void doStatusLineUpdate() { checkIfPathValid(); updateStatus(fContainerFieldStatus); } protected void checkIfPathValid() { fFolder= null; String pathStr= fContainerDialogField.getText(); if (pathStr.length() == 0) { fContainerFieldStatus.setError(NewWizardMessages.getString("NewContainerDialog.error.enterpath")); //$NON-NLS-1$ return; } IPath path= fCurrProject.getFullPath().append(pathStr); IWorkspace workspace= fCurrProject.getWorkspace(); IStatus pathValidation= workspace.validatePath(path.toString(), IResource.FOLDER); if (!pathValidation.isOK()) { fContainerFieldStatus.setError(NewWizardMessages.getFormattedString("NewContainerDialog.error.invalidpath", pathValidation.getMessage())); //$NON-NLS-1$ return; } IFolder folder= fCurrProject.getFolder(pathStr); if (isFolderExisting(folder)) { fContainerFieldStatus.setError(NewWizardMessages.getString("NewContainerDialog.error.pathexists")); //$NON-NLS-1$ return; } fContainerFieldStatus.setOK(); fFolder= folder; } private boolean isFolderExisting(IFolder folder) { for (int i= 0; i < fExistingFolders.length; i++) { if (folder.equals(fExistingFolders[i])) { return true; } } return false; } public IFolder getFolder() { return fFolder; } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class SourceContainerWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; private IJavaProject fCurrJProject; private IPath fProjPath; private Control fSWTControl; private IWorkspaceRoot fWorkspaceRoot; private SelectionButtonDialogField fProjectRadioButton; private SelectionButtonDialogField fFolderRadioButton; private ListDialogField fFoldersList; private CPListElement fProjectCPEntry; private StringDialogField fOutputLocationField; private boolean fIsProjSelected; public SourceContainerWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList, StringDialogField outputLocationField, boolean isNewProject) { fWorkspaceRoot= root; fClassPathList= classPathList; fProjectCPEntry= null; fOutputLocationField= outputLocationField; fSWTControl= null; SourceContainerAdapter adapter= new SourceContainerAdapter(); fProjectRadioButton= new SelectionButtonDialogField(SWT.RADIO); fProjectRadioButton.setDialogFieldListener(adapter); fProjectRadioButton.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.rb1.label")); //$NON-NLS-1$ fFolderRadioButton= new SelectionButtonDialogField(SWT.RADIO); fFolderRadioButton.setDialogFieldListener(adapter); fFolderRadioButton.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.rb2.label")); //$NON-NLS-1$ String[] buttonLabels; int removeIndex; if (isNewProject) { buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.addnew.button"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$ }; removeIndex= 2; } else { buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.addnew.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.addnew.addexisting.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$ }; removeIndex= 3; } fFoldersList= new ListDialogField(adapter, buttonLabels, new CPListLabelProvider()); fFoldersList.setDialogFieldListener(adapter); fFoldersList.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.label")); //$NON-NLS-1$ fFoldersList.setRemoveButtonIndex(removeIndex); fFolderRadioButton.attachDialogField(fFoldersList); } public void init(IJavaProject jproject) { fCurrJProject= jproject; fProjPath= fCurrJProject.getProject().getFullPath(); updateFoldersList(); } private void updateFoldersList() { fIsProjSelected= false; List srcelements= new ArrayList(fClassPathList.getSize()); List cpelements= fClassPathList.getElements(); for (int i= 0; i < cpelements.size(); i++) { CPListElement cpe= (CPListElement)cpelements.get(i); if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (fProjPath.equals(cpe.getPath())) { srcelements.clear(); // remember the entry to ensure a unique CPListElement for the project-cpentry fProjectCPEntry= cpe; fIsProjSelected= true; break; } else { srcelements.add(cpe); } } } fFoldersList.setElements(srcelements); // fix for 1G47IYV: ITPJUI:WINNT - Both radio buttons get selected in Project properties fFolderRadioButton.setSelection(!fIsProjSelected); fProjectRadioButton.setSelection(fIsProjSelected); } public Control getControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.numColumns= 2; composite.setLayout(layout); fProjectRadioButton.doFillIntoGrid(composite, 2); fFolderRadioButton.doFillIntoGrid(composite, 2); Control control= fFoldersList.getListControl(composite); MGridData gd= new MGridData(MGridData.FILL_BOTH); gd.horizontalIndent= 10; control.setLayoutData(gd); control= fFoldersList.getButtonBox(composite); gd= new MGridData(gd.VERTICAL_ALIGN_FILL + gd.HORIZONTAL_ALIGN_FILL); control.setLayoutData(gd); int buttonBarWidth= SWTUtil.convertWidthInCharsToPixels(24, composite); fFoldersList.setButtonsMinWidth(buttonBarWidth); fFoldersList.getTableViewer().setSorter(new CPListElementSorter()); fSWTControl= composite; return composite; } private Shell getShell() { if (fSWTControl != null) { return fSWTControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private class SourceContainerAdapter implements IListAdapter, IDialogFieldListener { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { sourcePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { sourcePageDialogFieldChanged(field); } } private void sourcePageCustomButtonPressed(DialogField field, int index) { if (field == fFoldersList) { List elementsToAdd= new ArrayList(10); switch (index) { case 0: /* add new */ CPListElement srcentry= createNewSourceContainer(); if (srcentry != null) { elementsToAdd.add(srcentry); } break; case 1: /* add existing */ CPListElement[] srcentries= chooseSourceContainers(); if (srcentries != null) { for (int i= 0; i < srcentries.length; i++) { elementsToAdd.add(srcentries[i]); } } break; } if (!elementsToAdd.isEmpty()) { fFoldersList.addElements(elementsToAdd); fFoldersList.postSetSelection(new StructuredSelection(elementsToAdd)); // if no source folders up to now if (fFoldersList.getSize() == elementsToAdd.size()) { askForChangingBuildPathDialog(); } } } } private void sourcePageDialogFieldChanged(DialogField field) { if (fCurrJProject == null) { // not initialized return; } if (field == fFolderRadioButton) { if (fFolderRadioButton.isSelected()) { fIsProjSelected= false; updateClasspathList(); if (fFoldersList.getSize() > 0) { askForChangingBuildPathDialog(); } } } else if (field == fProjectRadioButton) { if (fProjectRadioButton.isSelected()) { fIsProjSelected= true; updateClasspathList(); } } else if (field == fFoldersList) { updateClasspathList(); } } private void updateClasspathList() { List cpelements= fClassPathList.getElements(); List srcelements; if (fIsProjSelected) { srcelements= new ArrayList(1); if (fProjectCPEntry == null) { // never initialized before: create a new one fProjectCPEntry= newCPSourceElement(fCurrJProject.getProject()); } srcelements.add(fProjectCPEntry); } else { srcelements= fFoldersList.getElements(); } boolean changeDone= false; // backwards, as entries will be deleted for (int i= cpelements.size() - 1; i >= 0 ; i--) { CPListElement cpe= (CPListElement)cpelements.get(i); if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) { // if it is a source folder, but not one of the accepted entries, remove it // at the same time, for the entries seen, remove them from the accepted list if (!srcelements.remove(cpe)) { cpelements.remove(i); changeDone= true; } } } for (int i= 0; i < srcelements.size(); i++) { cpelements.add(srcelements.get(i)); } if (changeDone || (srcelements.size() > 0)) { fClassPathList.setElements(cpelements); } } private CPListElement createNewSourceContainer() { IProject proj= fCurrJProject.getProject(); String title= NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.title"); //$NON-NLS-1$ NewContainerDialog dialog= new NewContainerDialog(getShell(), title, proj, getExistingContainers()); dialog.setMessage(NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.NewSourceFolderDialog.description", fProjPath.toString())); //$NON-NLS-1$ if (dialog.open() == dialog.OK) { IFolder folder= dialog.getFolder(); return newCPSourceElement(folder); } return null; } /** * Asks to change the output folder to 'proj/bin' when no source folders were existing */ private void askForChangingBuildPathDialog() { IPath outputFolder= new Path(fOutputLocationField.getText()); if (outputFolder.segmentCount() == 1) { IPath newPath= outputFolder.append("bin"); String title= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.message", newPath); //$NON-NLS-1$ if (MessageDialog.openQuestion(getShell(), title, message)) { fOutputLocationField.setText(newPath.toString()); } } } private CPListElement[] chooseSourceContainers() { Class[] acceptedClasses= new Class[] { IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); acceptedClasses= new Class[] { IFolder.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getExistingContainers()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource)elements[i]; res[i]= newCPSourceElement(elem); } return res; } return null; } private IContainer[] getExistingContainers() { List res= new ArrayList(); List cplist= fFoldersList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IContainer) { // defensive code res.add(resource); } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } private CPListElement newCPSourceElement(IResource res) { Assert.isNotNull(res); return new CPListElement(IClasspathEntry.CPE_SOURCE, res.getFullPath(), res); } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { if (fIsProjSelected) { ArrayList list= new ArrayList(1); list.add(fProjectCPEntry); return list; } else { return fFoldersList.getSelectedElements(); } } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { if (!fIsProjSelected) { filterSelection(selElements, IClasspathEntry.CPE_SOURCE); fFoldersList.selectElements(new StructuredSelection(selElements)); } } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableCreationDialog.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.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.IUIConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.SWTUtil; 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.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class VariableCreationDialog extends StatusDialog { private IDialogSettings fDialogSettings; private StringDialogField fNameField; private StatusInfo fNameStatus; private StringButtonDialogField fPathField; private StatusInfo fPathStatus; private SelectionButtonDialogField fDirButton; private CPVariableElement fElement; private List fExistingNames; public VariableCreationDialog(Shell parent, CPVariableElement element, List existingNames) { super(parent); if (element == null) { setTitle(NewWizardMessages.getString("VariableCreationDialog.titlenew")); //$NON-NLS-1$ } else { setTitle(NewWizardMessages.getString("VariableCreationDialog.titleedit")); //$NON-NLS-1$ } fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); fElement= element; fNameStatus= new StatusInfo(); fPathStatus= new StatusInfo(); NewVariableAdapter adapter= new NewVariableAdapter(); fNameField= new StringDialogField(); fNameField.setDialogFieldListener(adapter); fNameField.setLabelText(NewWizardMessages.getString("VariableCreationDialog.name.label")); //$NON-NLS-1$ fPathField= new StringButtonDialogField(adapter); fPathField.setDialogFieldListener(adapter); fPathField.setLabelText(NewWizardMessages.getString("VariableCreationDialog.path.label")); //$NON-NLS-1$ fPathField.setButtonLabel(NewWizardMessages.getString("VariableCreationDialog.path.file.button")); //$NON-NLS-1$ fDirButton= new SelectionButtonDialogField(SWT.PUSH); fDirButton.setDialogFieldListener(adapter); fDirButton.setLabelText(NewWizardMessages.getString("VariableCreationDialog.path.dir.button")); //$NON-NLS-1$ fExistingNames= existingNames; if (element != null) { fNameField.setText(element.getName()); fPathField.setText(element.getPath().toString()); fExistingNames.remove(element.getName()); } else { fNameField.setText(""); //$NON-NLS-1$ fPathField.setText(""); //$NON-NLS-1$ } } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, new Object[] { IJavaHelpContextIds.VARIABLE_CREATION_DIALOG }); } public CPVariableElement getClasspathElement() { return new CPVariableElement(fNameField.getText(), new Path(fPathField.getText()), false); } /* * @see Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.marginWidth= 0; layout.numColumns= 3; inner.setLayout(layout); fNameField.doFillIntoGrid(inner, 2); DialogField.createEmptySpace(inner, 1); fPathField.doFillIntoGrid(inner, 3); DialogField.createEmptySpace(inner, 2); fDirButton.doFillIntoGrid(inner, 1); DialogField focusField= (fElement == null) ? fNameField : fPathField; focusField.postSetFocusOnDialogField(parent.getDisplay()); return composite; } // -------- NewVariableAdapter -------- private class NewVariableAdapter implements IDialogFieldListener, IStringButtonAdapter { // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { doFieldUpdated(field); } // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { doChangeControlPressed(field); } } private void doChangeControlPressed(DialogField field) { if (field == fPathField) { IPath path= chooseExtJarFile(); if (path != null) { fPathField.setText(path.toString()); } } } private void doFieldUpdated(DialogField field) { if (field == fNameField) { fNameStatus= nameUpdated(); } else if (field == fPathField) { fPathStatus= pathUpdated(); } else if (field == fDirButton) { IPath path= chooseExtDirectory(); if (path != null) { fPathField.setText(path.toString()); } } updateStatus(StatusUtil.getMoreSevere(fPathStatus, fNameStatus)); } private StatusInfo nameUpdated() { StatusInfo status= new StatusInfo(); String name= fNameField.getText(); if (name.length() == 0) { status.setError(NewWizardMessages.getString("VariableCreationDialog.error.entername")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateIdentifier(name); if (val.matches(IStatus.ERROR)) { status.setError(NewWizardMessages.getFormattedString("VariableCreationDialog.error.invalidname", val.getMessage())); //$NON-NLS-1$ } else if (nameConflict(name)) { status.setError(NewWizardMessages.getString("VariableCreationDialog.error.nameexists")); //$NON-NLS-1$ } return status; } private boolean nameConflict(String name) { if (fElement != null && fElement.getName().equals(name)) { return false; } for (int i= 0; i < fExistingNames.size(); i++) { CPVariableElement elem= (CPVariableElement)fExistingNames.get(i); if (name.equals(elem.getName())){ return true; } } return false; } private StatusInfo pathUpdated() { StatusInfo status= new StatusInfo(); String path= fPathField.getText(); if (path.length() > 0) { // empty path is ok if (!Path.ROOT.isValidPath(path)) { status.setError(NewWizardMessages.getString("VariableCreationDialogerror.invalidpath")); //$NON-NLS-1$ } else if (!new File(path).exists()) { status.setWarning(NewWizardMessages.getString("VariableCreationDialog.warning.pathnotexists")); //$NON-NLS-1$ } } return status; } private String getInitPath() { String initPath= fPathField.getText(); if (initPath.length() == 0) { initPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR); if (initPath == null) { initPath= ""; //$NON-NLS-1$ } } else { IPath entryPath= new Path(initPath); if (ArchiveFileFilter.isArchivePath(entryPath)) { entryPath.removeLastSegments(1); } initPath= entryPath.toOSString(); } return initPath; } /* * Open a dialog to choose a jar from the file system */ private IPath chooseExtJarFile() { String initPath= getInitPath(); FileDialog dialog= new FileDialog(getShell()); dialog.setText(NewWizardMessages.getString("VariableCreationDialog.extjardialog.text")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(initPath); String res= dialog.open(); if (res != null) { fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath()); return new Path(res).makeAbsolute(); } return null; } private IPath chooseExtDirectory() { String initPath= getInitPath(); DirectoryDialog dialog= new DirectoryDialog(getShell()); dialog.setText(NewWizardMessages.getString("VariableCreationDialog.extdirdialog.text")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("VariableCreationDialog.extdirdialog.message")); //$NON-NLS-1$ dialog.setFilterPath(initPath); String res= dialog.open(); if (res != null) { fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath()); return new Path(res); } return null; } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableSelectionBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.JavaCore; 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.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; 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.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class VariableSelectionBlock { private List fExistingPaths; private StringButtonDialogField fVariableField; private StringButtonDialogField fExtensionField; private CLabel fFullPath; private IStatus fVariableStatus; private IStatus fExistsStatus; private IStatus fExtensionStatus; private String fVariable; private IStatusChangeListener fContext; private boolean fIsEmptyAllowed; private String fLastVariableSelection; /** * Constructor for VariableSelectionBlock */ public VariableSelectionBlock(IStatusChangeListener context, List existingPaths, IPath varPath, String lastVarSelection, boolean emptyAllowed) { fContext= context; fExistingPaths= existingPaths; fIsEmptyAllowed= emptyAllowed; fLastVariableSelection= lastVarSelection; fVariableStatus= new StatusInfo(); fExistsStatus= new StatusInfo(); VariableSelectionAdapter adapter= new VariableSelectionAdapter(); fVariableField= new StringButtonDialogField(adapter); fVariableField.setDialogFieldListener(adapter); fVariableField.setLabelText(NewWizardMessages.getString("VariableSelectionBlock.variable.label")); //$NON-NLS-1$ fVariableField.setButtonLabel(NewWizardMessages.getString("VariableSelectionBlock.variable.button")); //$NON-NLS-1$ fExtensionField= new StringButtonDialogField(adapter); fExtensionField.setDialogFieldListener(adapter); fExtensionField.setLabelText(NewWizardMessages.getString("VariableSelectionBlock.extension.label")); //$NON-NLS-1$ fExtensionField.setButtonLabel(NewWizardMessages.getString("VariableSelectionBlock.extension.button")); //$NON-NLS-1$ if (varPath != null) { fVariableField.setText(varPath.segment(0)); fExtensionField.setText(varPath.removeFirstSegments(1).toString()); } else { fVariableField.setText(""); //$NON-NLS-1$ fExtensionField.setText(""); //$NON-NLS-1$ } updateFullTextField(); } public IPath getVariablePath() { if (fVariable != null) { return new Path(fVariable).append(fExtensionField.getText()); } return null; } public IPath getResolvedPath() { if (fVariable != null) { IPath entryPath= JavaCore.getClasspathVariable(fVariable); if (entryPath != null) { return entryPath.append(fExtensionField.getText()); } } return null; } public void doFillIntoGrid(Composite inner, int nColumns) { fVariableField.doFillIntoGrid(inner, nColumns); fExtensionField.doFillIntoGrid(inner, nColumns); Label label= new Label(inner, SWT.LEFT); label.setLayoutData(new MGridData()); label.setText(NewWizardMessages.getString("VariableSelectionBlock.fullpath.label")); //$NON-NLS-1$ fFullPath= new CLabel(inner, SWT.NONE); fFullPath.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(inner, nColumns - 2); updateFullTextField(); } public void setFocus(Display display) { fVariableField.postSetFocusOnDialogField(display); } public Control createControl(Composite parent) { Composite inner= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, inner); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 3; inner.setLayout(layout); doFillIntoGrid(inner, 3); setFocus(parent.getDisplay()); return inner; } // -------- VariableSelectionAdapter -------- private class VariableSelectionAdapter implements IDialogFieldListener, IStringButtonAdapter { // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { doFieldUpdated(field); } // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { doChangeControlPressed(field); } } private void doChangeControlPressed(DialogField field) { if (field == fVariableField) { String variable= chooseVariable(); if (variable != null) { fVariableField.setText(variable); } } else if (field == fExtensionField) { IPath filePath= chooseExtJar(); if (filePath != null) { fExtensionField.setText(filePath.toString()); } } } private void doFieldUpdated(DialogField field) { if (field == fVariableField) { fVariableStatus= variableUpdated(); } else if (field == fExtensionField) { fExtensionStatus= extensionUpdated(); } fExistsStatus= getExistsStatus(); updateFullTextField(); fContext.statusChanged(StatusUtil.getMostSevere(new IStatus[] { fVariableStatus, fExtensionStatus, fExistsStatus })); } private IStatus variableUpdated() { fVariable= null; StatusInfo status= new StatusInfo(); String name= fVariableField.getText(); if (name.length() == 0) { if (!fIsEmptyAllowed) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.entername")); //$NON-NLS-1$ } else { fVariable= ""; //$NON-NLS-1$ } } else if (JavaCore.getClasspathVariable(name) == null) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.namenotexists")); //$NON-NLS-1$ } else { fVariable= name; } fExtensionField.enableButton(fVariable != null); return status; } private IStatus extensionUpdated() { StatusInfo status= new StatusInfo(); String extension= fExtensionField.getText(); if (extension.length() > 0 && !Path.ROOT.isValidPath(extension)) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.invalidextension")); //$NON-NLS-1$ } return status; } private IStatus getExistsStatus() { StatusInfo status= new StatusInfo(); IPath path= getResolvedPath(); if (path != null) { if (findPath(path)) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.pathexists")); //$NON-NLS-1$ } else if (!path.toFile().isFile()) { status.setWarning(NewWizardMessages.getString("VariableSelectionBlock.warning.pathnotexists")); //$NON-NLS-1$ } } else { status.setWarning(NewWizardMessages.getString("VariableSelectionBlock.warning.pathnotexists")); //$NON-NLS-1$ } return status; } private boolean findPath(IPath path) { for (int i= fExistingPaths.size() -1; i >=0; i--) { IPath curr= (IPath) fExistingPaths.get(i); if (curr.equals(path)) { return true; } } return false; } private void updateFullTextField() { if (fFullPath != null && !fFullPath.isDisposed()) { IPath resolvedPath= getResolvedPath(); if (resolvedPath != null) { fFullPath.setText(resolvedPath.toOSString()); } else { fFullPath.setText(""); //$NON-NLS-1$ } } } private Shell getShell() { if (fFullPath != null) { return fFullPath.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private IPath chooseExtJar() { String lastUsedPath= ""; //$NON-NLS-1$ IPath entryPath= getResolvedPath(); if (entryPath != null) { if (ArchiveFileFilter.isArchivePath(entryPath)) { lastUsedPath= entryPath.removeLastSegments(1).toOSString(); } else { lastUsedPath= entryPath.toOSString(); } } FileDialog dialog= new FileDialog(getShell(), SWT.SINGLE); dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(lastUsedPath); dialog.setText(NewWizardMessages.getString("VariableSelectionBlock.ExtJarDialog.title")); //$NON-NLS-1$ String res= dialog.open(); if (res == null) { return null; } IPath resPath= new Path(res).makeAbsolute(); IPath varPath= JavaCore.getClasspathVariable(fVariable); if (!varPath.isPrefixOf(resPath)) { return new Path(resPath.lastSegment()); } else { return resPath.removeFirstSegments(varPath.segmentCount()).setDevice(null); } } private String chooseVariable() { String selecteVariable= (fVariable != null) ? fVariable : fLastVariableSelection; ChooseVariableDialog dialog= new ChooseVariableDialog(getShell(), selecteVariable); if (dialog.open() == dialog.OK) { return dialog.getSelectedVariable(); } return null; } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Table; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.TableViewer; /** * A list with checkboxes and a button bat. Typical buttons are 'Check All' and 'Uncheck All'. * List model is independend of widget creation. * DialogFields controls are: Label, List and Composite containing buttons. */ public class CheckedListDialogField extends ListDialogField { private int fCheckAllButtonIndex; private int fUncheckAllButtonIndex; private List fCheckElements; public CheckedListDialogField(IListAdapter adapter, String[] customButtonLabels, ILabelProvider lprovider) { super(adapter, customButtonLabels, lprovider); fCheckElements= new ArrayList(); fCheckAllButtonIndex= -1; fUncheckAllButtonIndex= -1; } /** * Sets the index of the 'check' button in the button label array passed in the constructor. * The behaviour of the button marked as the check button will then be handled internally. * (enable state, button invocation behaviour) */ public void setCheckAllButtonIndex(int checkButtonIndex) { Assert.isTrue(checkButtonIndex < fButtonLabels.length); fCheckAllButtonIndex= checkButtonIndex; } /** * Sets the index of the 'uncheck' button in the button label array passed in the constructor. * The behaviour of the button marked as the uncheck button will then be handled internally. * (enable state, button invocation behaviour) */ public void setUncheckAllButtonIndex(int uncheckButtonIndex) { Assert.isTrue(uncheckButtonIndex < fButtonLabels.length); fUncheckAllButtonIndex= uncheckButtonIndex; } /* * @see ListDialogField#createTableViewer */ protected TableViewer createTableViewer(Composite parent) { Table table= new Table(parent, SWT.CHECK + getListStyle()); CheckboxTableViewer tableViewer= new CheckboxTableViewer(table); tableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent e) { doCheckStateChanged(e); } }); return tableViewer; } /* * @see ListDialogField#getListControl */ public Control getListControl(Composite parent) { Control control= super.getListControl(parent); ((CheckboxTableViewer)fTable).setCheckedElements(fCheckElements.toArray()); return control; } /* * @see DialogField#dialogFieldChanged * Hooks in to get element changes to update check model. */ public void dialogFieldChanged() { for (int i= fCheckElements.size() -1; i >= 0; i--) { if (!fElements.contains(fCheckElements.get(i))) { fCheckElements.remove(i); } } super.dialogFieldChanged(); } private void checkStateChanged() { //call super and do not update check model super.dialogFieldChanged(); } /** * Gets the checked elements. */ public List getCheckedElements() { return new ArrayList(fCheckElements); } /** * Returns true if the element is checked. */ public boolean isChecked(Object obj) { return fCheckElements.contains(obj); } /** * Sets the checked elements. */ public void setCheckedElements(List list) { fCheckElements= new ArrayList(list); if (fTable != null) { ((CheckboxTableViewer)fTable).setCheckedElements(list.toArray()); } checkStateChanged(); } /** * Sets the checked state of an element. */ public void setChecked(Object object, boolean state) { setCheckedWithoutUpdate(object, state); checkStateChanged(); } /** * Sets the checked state of an element. no dialog changed listener informed */ public void setCheckedWithoutUpdate(Object object, boolean state) { if (!fCheckElements.contains(object)) { fCheckElements.add(object); } if (fTable != null) { ((CheckboxTableViewer)fTable).setChecked(object, state); } } /** * Sets the check state of all elements */ public void checkAll(boolean state) { if (state) { fCheckElements= getElements(); } else { fCheckElements.clear(); } if (fTable != null) { ((CheckboxTableViewer)fTable).setAllChecked(state); } checkStateChanged(); } private void doCheckStateChanged(CheckStateChangedEvent e) { if (e.getChecked()) { fCheckElements.add(e.getElement()); } else { fCheckElements.remove(e.getElement()); } checkStateChanged(); } // ------ enable / disable management /* * @see ListDialogField#getManagedButtonState */ protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fCheckAllButtonIndex) { return !fElements.isEmpty(); } else if (index == fUncheckAllButtonIndex) { return !fElements.isEmpty(); } return super.getManagedButtonState(sel, index); } /* * @see ListDialogField#extraButtonPressed */ protected boolean managedButtonPressed(int index) { if (index == fCheckAllButtonIndex) { checkAll(true); } else if (index == fUncheckAllButtonIndex) { checkAll(false); } else { return super.managedButtonPressed(index); } return true; } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/DialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; 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.jface.dialogs.IDialogConstants; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; /** * Base class of all dialog fields. * Dialog fields manage controls together with the model, independed * from the creation time of the widgets. * - support for automated layouting. * - enable / disable, set focus a concept of the base class. * * DialogField have a label. */ public class DialogField { private Label fLabel; protected String fLabelText; private IDialogFieldListener fDialogFieldListener; private boolean fEnabled; public DialogField() { fEnabled= true; fLabel= null; fLabelText= ""; //$NON-NLS-1$ } /** * Sets the label of the dialog field. */ public void setLabelText(String labeltext) { fLabelText= labeltext; } // ------ change listener /** * Defines the listener for this dialog field. */ public final void setDialogFieldListener(IDialogFieldListener listener) { fDialogFieldListener= listener; } /** * Programatical invocation of a dialog field change. */ public void dialogFieldChanged() { if (fDialogFieldListener != null) { fDialogFieldListener.dialogFieldChanged(this); } } // ------- focus management /** * Tries to set the focus to the dialog field. * Returns <code>true</code> if the dialog field can take focus. * To be reimplemented by dialog field implementors. */ public boolean setFocus() { return false; } /** * Posts <code>setFocus</code> to the display event queue. */ public void postSetFocusOnDialogField(Display display) { if (display != null) { display.asyncExec( new Runnable() { public void run() { setFocus(); } } ); } } // ------- layout helpers /** * Creates all controls of the dialog field and fills it to a composite. * The composite is assumed to have <code>MGridLayout</code> as * layout. * The dialog field will adjust its controls' spans to the number of columns given. * To be reimplemented by dialog field implementors. */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); Label label= getLabelControl(parent); label.setLayoutData(gridDataForLabel(nColumns)); return new Control[] { label }; } /** * Returns the number of columns of the dialog field. * To be reimplemented by dialog field implementors. */ public int getNumberOfControls() { return 1; } protected static MGridData gridDataForLabel(int span) { MGridData gd= new MGridData(); gd.horizontalSpan= span; return gd; } // ------- ui creation /** * Creates or returns the created label widget. * @param parent The parent composite or <code>null</code> if the widget has * already been created. */ public Label getLabelControl(Composite parent) { if (fLabel == null) { assertCompositeNotNull(parent); fLabel= new Label(parent, SWT.LEFT); fLabel.setFont(parent.getFont()); fLabel.setEnabled(fEnabled); if (fLabelText != null && !"".equals(fLabelText)) { //$NON-NLS-1$ fLabel.setText(fLabelText); } else { // XXX: to avoid a 16 pixel wide empty label - revisit fLabel.setText("."); //$NON-NLS-1$ fLabel.setVisible(false); } } return fLabel; } /** * Creates a spacer control. * @param parent The parent composite */ public static Control createEmptySpace(Composite parent) { return createEmptySpace(parent, 1); } /** * Creates a spacer control with the given span. * The composite is assumed to have <code>MGridLayout</code> as * layout. * @param parent The parent composite */ public static Control createEmptySpace(Composite parent, int span) { Label label= new Label(parent, SWT.LEFT); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.BEGINNING; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= span; gd.horizontalIndent= 0; gd.widthHint= 0; gd.heightHint= 0; label.setLayoutData(gd); return label; } /** * Tests is the control is not <code>null</code> and not disposed. */ protected final boolean isOkToUse(Control control) { return (control != null) && !(control.isDisposed()); } // --------- enable / disable management /** * Sets the enable state of the dialog field. */ public final void setEnabled(boolean enabled) { if (enabled != fEnabled) { fEnabled= enabled; updateEnableState(); } } /** * Called when the enable state changed. * To be extended by dialog field implementors. */ protected void updateEnableState() { if (fLabel != null) { fLabel.setEnabled(fEnabled); } } /** * Gets the enable state of the dialog field. */ public final boolean isEnabled() { return fEnabled; } protected final void assertCompositeNotNull(Composite comp) { Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$ } protected final void assertEnoughColumns(int nColumns) { Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$ } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/LayoutUtil.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class LayoutUtil { /** * Calculates the number of columns needed by field editors */ public static int getNumberOfColumns(DialogField[] editors) { int nCulumns= 0; for (int i= 0; i < editors.length; i++) { nCulumns= Math.max(editors[i].getNumberOfControls(), nCulumns); } return nCulumns; } /** * Creates a composite and fills in the given editors. * @param labelOnTop Defines if the label of all fields should be on top of the fields */ public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop) { doDefaultLayout(parent, editors, labelOnTop, 0, 0, 0, 0); } /** * Creates a composite and fills in the given editors. * @param labelOnTop Defines if the label of all fields should be on top of the fields * @param minWidth The minimal width of the composite * @param minHeight The minimal height of the composite */ public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight) { doDefaultLayout(parent, editors, labelOnTop, minWidth, minHeight, 0, 0); } /** * Creates a composite and fills in the given editors. * @param labelOnTop Defines if the label of all fields should be on top of the fields * @param minWidth The minimal width of the composite * @param minHeight The minimal height of the composite * @param marginWidth The margin width to be used by the composite * @param marginHeight The margin height to be used by the composite */ public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight, int marginWidth, int marginHeight) { int nCulumns= getNumberOfColumns(editors); Control[][] controls= new Control[editors.length][]; for (int i= 0; i < editors.length; i++) { controls[i]= editors[i].doFillIntoGrid(parent, nCulumns); } if (labelOnTop) { nCulumns--; modifyLabelSpans(controls, nCulumns); } MGridLayout layout= new MGridLayout(); if (marginWidth != SWT.DEFAULT) { layout.marginWidth= marginWidth; } if (marginHeight != SWT.DEFAULT) { layout.marginHeight= marginHeight; } layout.minimumWidth= minWidth; layout.minimumHeight= minHeight; layout.numColumns= nCulumns; parent.setLayout(layout); } private static void modifyLabelSpans(Control[][] controls, int nCulumns) { for (int i= 0; i < controls.length; i++) { setHorizontalSpan(controls[i][0], nCulumns); } } /** * Sets the span of a control. Assumes that MGriddata is used. */ public static void setHorizontalSpan(Control control, int span) { Object ld= control.getLayoutData(); if (ld instanceof MGridData) { ((MGridData)ld).horizontalSpan= span; } else if (span != 1) { MGridData gd= new MGridData(); gd.horizontalSpan= span; control.setLayoutData(gd); } } }
6,207
Bug 6207 Java project properties dialog grows taller than screen
build 20011116 The Java Build Path/Order page in the project properties dialog always grows the table to show all items. In a workspace with many source folders the properties dialog grows so tall that you can no longer see the ok/cancel buttons. I noticed this while using WSDD (Eclipse 1.0 based) to create P3ML bundles. P3ML consists of about 20 bundles with each bundle living in a separate source folder. Note that the resize only happens when the dialog is reopened. If you create source folders in the properties dialog and then switch to the order page you will see scroll bars. Also, it seems that this only happens when there is a large number of source folders. When I reference a lot of projects the height of the order page is limited and the table shows scroll bars.
resolved fixed
1b69a90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:07:47Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; 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.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; 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.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; /** * A list with a button bar. * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. * List model is independend of widget creation. * DialogFields controls are: Label, List and Composite containing buttons. */ public class ListDialogField extends DialogField { protected TableViewer fTable; protected ILabelProvider fLabelProvider; protected ListViewerAdapter fListViewerAdapter; protected List fElements; protected String[] fButtonLabels; private Button[] fButtonControls; private boolean[] fButtonsEnabled; private int fRemoveButtonIndex; private int fUpButtonIndex; private int fDownButtonIndex; private Label fLastSeparator; private Table fTableControl; private Composite fButtonsControl; private ISelection fSelectionWhenEnabled; private TableColumn fTableColumn; private IListAdapter fListAdapter; private Object fParentElement; /** * Creates the <code>ListDialogField</code>. * @param adapter A listener for button invocation, selection changes. * @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and * marks a separator. * @param lprovider The label provider to render the table entries */ public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) { super(); fListAdapter= adapter; fLabelProvider= lprovider; fListViewerAdapter= new ListViewerAdapter(); fParentElement= this; fElements= new ArrayList(10); fButtonLabels= buttonLabels; if (fButtonLabels != null) { int nButtons= fButtonLabels.length; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsEnabled[i]= true; } } fTable= null; fTableControl= null; fButtonsControl= null; fRemoveButtonIndex= -1; fUpButtonIndex= -1; fDownButtonIndex= -1; } /** * Sets the index of the 'remove' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'remove' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); fRemoveButtonIndex= removeButtonIndex; } /** * Sets the index of the 'up' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'up' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); fUpButtonIndex= upButtonIndex; } /** * Sets the index of the 'down' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'down' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); fDownButtonIndex= downButtonIndex; } // ------ adapter communication private void buttonPressed(int index) { if (!managedButtonPressed(index)) { fListAdapter.customButtonPressed(this, index); } } /** * Checks if the button pressed is handled internally * @return Returns true if button has been handled. */ protected boolean managedButtonPressed(int index) { if (index == fRemoveButtonIndex) { remove(); } else if (index == fUpButtonIndex) { up(); } else if (index == fDownButtonIndex) { down(); } else { return false; } return true; } // ------ layout helpers /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); Label label= getLabelControl(parent); MGridData gd= gridDataForLabel(1); gd.verticalAlignment= gd.BEGINNING; label.setLayoutData(gd); Control list= getListControl(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= true; gd.grabColumn= 0; gd.horizontalSpan= nColumns - 2; list.setLayoutData(gd); Composite buttons= getButtonBox(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= false; gd.horizontalSpan= 1; buttons.setLayoutData(gd); return new Control[] { label, list, buttons }; } /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { return 3; } /** * Sets the minimal width of the buttons. Must be called after widget creation. */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { ((MGridData)fLastSeparator.getLayoutData()).widthHint= minWidth; } } // ------ ui creation /** * Returns the list control. When called the first time, the control will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Control getListControl(Composite parent) { if (fTableControl == null) { assertCompositeNotNull(parent); fTable= createTableViewer(parent); fTable.setContentProvider(fListViewerAdapter); fTable.setLabelProvider(fLabelProvider); fTable.addSelectionChangedListener(fListViewerAdapter); fTableControl= (Table)fTable.getControl(); // Add a table column. TableLayout tableLayout= new TableLayout(); tableLayout.addColumnData(new ColumnWeightData(100)); fTableColumn= new TableColumn(fTableControl, SWT.NONE); fTableColumn.setResizable(false); fTableControl.setLayout(tableLayout); fTable.setInput(fParentElement); fTableControl.setEnabled(isEnabled()); if (fSelectionWhenEnabled != null) { postSetSelection(fSelectionWhenEnabled); } fTableColumn.getDisplay().asyncExec(new Runnable() { public void run() { if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } } }); } return fTableControl; } /** * Returns the internally used table viewer. */ public TableViewer getTableViewer() { return fTable; } /* * Subclasses may override to specify a different style. */ protected int getListStyle(){ return SWT.BORDER + SWT.MULTI + SWT.H_SCROLL + SWT.V_SCROLL; } protected TableViewer createTableViewer(Composite parent) { Table table= new Table(parent, getListStyle()); return new TableViewer(table); } protected Button createButton(Composite parent, String label, SelectionListener listener) { Button button= new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(listener); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.BEGINNING; gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); return button; } private Label createSeparator(Composite parent) { Label separator= new Label(parent, SWT.NONE); separator.setVisible(false); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.verticalAlignment= gd.BEGINNING; gd.heightHint= 4; separator.setLayoutData(gd); return separator; } /** * Returns the composite containing the buttons. When called the first time, the control * will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; Composite contents= new Composite(parent, SWT.NULL); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; contents.setLayout(layout); if (fButtonLabels != null) { fButtonControls= new Button[fButtonLabels.length]; for (int i= 0; i < fButtonLabels.length; i++) { String currLabel= fButtonLabels[i]; if (currLabel != null) { fButtonControls[i]= createButton(contents, currLabel, listener); fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); } else { fButtonControls[i]= null; createSeparator(contents); } } } fLastSeparator= createSeparator(contents); updateButtonState(); fButtonsControl= contents; } return fButtonsControl; } private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { for (int i= 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; } } } } // ------ enable / disable management /* * @see DialogField#dialogFieldChanged */ public void dialogFieldChanged() { super.dialogFieldChanged(); if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } updateButtonState(); } private Button getButton(int index) { if (fButtonControls != null && index >= 0 && index < fButtonControls.length) { return fButtonControls[index]; } return null; } /* * Updates the enable state of the all buttons */ protected void updateButtonState() { if (fButtonControls != null) { ISelection sel= fTable.getSelection(); for (int i= 0; i < fButtonControls.length; i++) { Button button= fButtonControls[i]; if (isOkToUse(button)) { boolean extraState= getManagedButtonState(sel, i); button.setEnabled(isEnabled() && extraState && fButtonsEnabled[i]); } } } } protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fRemoveButtonIndex) { return !sel.isEmpty(); } else if (index == fUpButtonIndex) { return !sel.isEmpty() && canMoveUp(); } else if (index == fDownButtonIndex) { return !sel.isEmpty() && canMoveDown(); } return true; } /* * @see DialogField#updateEnableState */ protected void updateEnableState() { super.updateEnableState(); boolean enabled= isEnabled(); if (isOkToUse(fTableControl)) { if (!enabled) { fSelectionWhenEnabled= fTable.getSelection(); selectElements(null); } else { selectElements(fSelectionWhenEnabled); fSelectionWhenEnabled= null; } fTableControl.setEnabled(enabled); } updateButtonState(); } /** * Sets a button enabled or disabled. */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { fButtonsEnabled[index]= enable; updateButtonState(); } } // ------ model access /** * Sets the elements shown in the list. */ public void setElements(List elements) { fElements= new ArrayList(elements); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } /** * Gets the elements shown in the list. * The list returned is a copy, so it can be modified by the user. */ public List getElements() { return new ArrayList(fElements); } /** * Gets the elements shown at the given index. */ public Object getElement(int index) { return fElements.get(index); } /** * Replace an element. */ public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException { int idx= fElements.indexOf(oldElement); if (idx != -1) { if (oldElement.equals(newElement) || fElements.contains(newElement)) { return; } fElements.set(idx, newElement); if (fTable != null) { List selected= getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } fTable.refresh(); fTable.setSelection(new StructuredSelection(selected)); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Adds an element at the end of the list. */ public void addElement(Object element) { if (fElements.contains(element)) { return; } fElements.add(element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds elements at the end of the list. */ public void addElements(List elements) { int nElements= elements.size(); if (nElements > 0) { // filter duplicated ArrayList elementsToAdd= new ArrayList(nElements); for (int i= 0; i < nElements; i++) { Object elem= elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); } } fElements.addAll(elementsToAdd); if (fTable != null) { fTable.add(elementsToAdd.toArray()); } dialogFieldChanged(); } } /** * Adds an element at a position. */ public void insertElementAt(Object element, int index) { if (fElements.contains(element)) { return; } fElements.add(index, element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds an element at a position. */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } } /** * Removes an element from the list. */ public void removeElement(Object element) throws IllegalArgumentException { if (fElements.remove(element)) { if (fTable != null) { fTable.remove(element); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Removes elements from the list. */ public void removeElements(List elements) { if (elements.size() > 0) { fElements.removeAll(elements); if (fTable != null) { fTable.remove(elements.toArray()); } dialogFieldChanged(); } } /** * Gets the number of elements */ public int getSize() { return fElements.size(); } public void selectElements(ISelection selection) { fSelectionWhenEnabled= selection; if (fTable != null) { fTable.setSelection(selection); } } public void postSetSelection(final ISelection selection) { if (isOkToUse(fTableControl)) { Display d= fTableControl.getDisplay(); d.asyncExec(new Runnable() { public void run() { if (isOkToUse(fTableControl)) { selectElements(selection); } } }); } } /** * Refreshes the table. */ public void refresh() { fTable.refresh(); } // ------- list maintenance private List moveUp(List elements, List move) { int nElements= elements.size(); List res= new ArrayList(nElements); Object floating= null; for (int i= 0; i < nElements; i++) { Object curr= elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } floating= curr; } } if (floating != null) { res.add(floating); } return res; } private void moveUp(List toMoveUp) { if (toMoveUp.size() > 0) { setElements(moveUp(fElements, toMoveUp)); fTable.reveal(toMoveUp.get(0)); } } private void moveDown(List toMoveDown) { if (toMoveDown.size() > 0) { setElements(reverse(moveUp(reverse(fElements), toMoveDown))); fTable.reveal(toMoveDown.get(toMoveDown.size() - 1)); } } private List reverse(List p) { List reverse= new ArrayList(p.size()); for (int i= p.size()-1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; } private void remove() { removeElements(getSelectedElements()); } private void up() { moveUp(getSelectedElements()); } private void down() { moveDown(getSelectedElements()); } private boolean canMoveUp() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); for (int i= 0; i < indc.length; i++) { if (indc[i] != i) { return true; } } } return false; } private boolean canMoveDown() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); int k= fElements.size() - 1; for (int i= indc.length - 1; i >= 0 ; i--, k--) { if (indc[i] != k) { return true; } } } return false; } /** * Returns the selected elements. */ public List getSelectedElements() { List result= new ArrayList(); if (fTable != null) { ISelection selection= fTable.getSelection(); if (selection instanceof IStructuredSelection) { Iterator iter= ((IStructuredSelection)selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } } } return result; } // ------- ListViewerAdapter private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener { // ------- ITableContentProvider Interface ------------ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // will never happen } public boolean isDeleted(Object element) { return false; } public void dispose() { } public Object[] getElements(Object obj) { return fElements.toArray(); } // ------- ISelectionChangedListener Interface ------------ public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } } private void doListSelected(SelectionChangedEvent event) { updateButtonState(); if (fListAdapter != null) { fListAdapter.selectionChanged(this); } } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class BuildPathsBlock { private IWorkspaceRoot fWorkspaceRoot; private CheckedListDialogField fClassPathList; private StringDialogField fBuildPathDialogField; private StatusInfo fClassPathStatus; private StatusInfo fBuildPathStatus; private IJavaProject fCurrJProject; private IPath fOutputLocationPath; private IStatusChangeListener fContext; private Control fSWTWidget; private boolean fIsNewProject; private SourceContainerWorkbookPage fSourceContainerPage; private ProjectsWorkbookPage fProjectsPage; private LibrariesWorkbookPage fLibrariesPage; private BuildPathBasePage fCurrPage; public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean isNewProject) { fWorkspaceRoot= root; fContext= context; fIsNewProject= isNewProject; fSourceContainerPage= null; fLibrariesPage= null; fProjectsPage= null; fCurrPage= null; BuildPathAdapter adapter= new BuildPathAdapter(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$ }; fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fClassPathList.setDialogFieldListener(adapter); fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); fClassPathList.setUpButtonIndex(0); fClassPathList.setDownButtonIndex(1); fClassPathList.setCheckAllButtonIndex(3); fClassPathList.setUncheckAllButtonIndex(4); if (isNewProject) { fBuildPathDialogField= new StringDialogField(); } else { StringButtonDialogField dialogField= new StringButtonDialogField(adapter); dialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$ fBuildPathDialogField= dialogField; } fBuildPathDialogField.setDialogFieldListener(adapter); fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$ fBuildPathStatus= new StatusInfo(); fClassPathStatus= new StatusInfo(); fCurrJProject= null; } // -------- UI creation --------- public Control createControl(Composite parent) { fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, parent); layout.minimumHeight= SWTUtil.convertHeightInCharsToPixels(20, parent); layout.numColumns= 1; composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new MGridData(MGridData.FILL_BOTH)); folder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabChanged(e.item); } }); ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry(); TabItem item; fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField, fIsNewProject); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT)); item.setData(fSourceContainerPage); item.setControl(fSourceContainerPage.getControl(folder)); IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); fProjectsPage= new ProjectsWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$ item.setImage(projectImage); item.setData(fProjectsPage); item.setControl(fProjectsPage.getControl(folder)); fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY)); item.setData(fLibrariesPage); item.setControl(fLibrariesPage.getControl(folder)); // a non shared image Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage(); composite.addDisposeListener(new ImageDisposer(cpoImage)); ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$ item.setImage(cpoImage); item.setData(ordpage); item.setControl(ordpage.getControl(folder)); if (fCurrJProject != null) { fSourceContainerPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); } Composite editorcomp= new Composite(composite, SWT.NONE); DialogField[] editors= new DialogField[] { fBuildPathDialogField }; LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0, 0, 0); int maxFieldWidth= SWTUtil.convertWidthInCharsToPixels(40, parent); LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth); editorcomp.setLayoutData(new MGridData(MGridData.FILL_HORIZONTAL)); if (fIsNewProject) { folder.setSelection(0); fCurrPage= fSourceContainerPage; } else { folder.setSelection(3); fCurrPage= ordpage; } WorkbenchHelp.setHelp(composite, new Object[] { IJavaHelpContextIds.BUILD_PATH_BLOCK }); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Initializes the classpath for the given project. Multiple calls to init are allowed, * but all existing settings will be cleared and replace by the given or default paths. * @param project The java project to configure. Does not have to exist. * @param outputLocation The output location to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * output location of the existing project * @param classpathEntries The classpath entries to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * classpath entries of the existing project */ public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) { fCurrJProject= jproject; boolean projExists= false; try { IProject project= fCurrJProject.getProject(); projExists= (project.exists() && project.hasNature(JavaCore.NATURE_ID)); if (projExists) { if (outputLocation == null) { outputLocation= fCurrJProject.getOutputLocation(); } if (classpathEntries == null) { classpathEntries= fCurrJProject.getRawClasspath(); } } } catch (CoreException e) { JavaPlugin.log(e.getStatus()); } if (outputLocation == null) { outputLocation= getDefaultBuildPath(jproject); } List newClassPath; if (classpathEntries == null) { newClassPath= getDefaultClassPath(jproject); } else { newClassPath= new ArrayList(); for (int i= 0; i < classpathEntries.length; i++) { IClasspathEntry curr= classpathEntries[i]; int entryKind= curr.getEntryKind(); IPath path= curr.getPath(); boolean isExported= curr.isExported(); // get the resource IResource res= null; boolean isMissing= false; if (entryKind != IClasspathEntry.CPE_VARIABLE) { res= fWorkspaceRoot.findMember(path); if (res == null) { isMissing= (entryKind != IClasspathEntry.CPE_LIBRARY || !path.toFile().isFile()); } } else { IPath resolvedPath= JavaCore.getResolvedVariablePath(path); isMissing= (resolvedPath == null) || !resolvedPath.toFile().isFile(); } CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported); if (projExists) { elem.setIsMissing(isMissing); } newClassPath.add(elem); } } List exportedEntries = new ArrayList(); for (int i= 0; i < newClassPath.size(); i++) { CPListElement curr= (CPListElement) newClassPath.get(i); if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { exportedEntries.add(curr); } } // inits the dialog field fBuildPathDialogField.setText(outputLocation.makeRelative().toString()); fClassPathList.setElements(newClassPath); fClassPathList.setCheckedElements(exportedEntries); if (fSourceContainerPage != null) { fSourceContainerPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); } doStatusLineUpdate(); } // -------- public api -------- /** * Returns the Java project. Can return <code>null<code> if the page has not * been initialized. */ public IJavaProject getJavaProject() { return fCurrJProject; } /** * Returns the current output location. Note that the path returned must not be valid. */ public IPath getOutputLocation() { return new Path(fBuildPathDialogField.getText()).makeAbsolute(); } /** * Returns the current class path (raw). Note that the entries returned must not be valid. */ public IClasspathEntry[] getRawClassPath() { List elements= fClassPathList.getElements(); int nElements= elements.size(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= 0; i < nElements; i++) { CPListElement currElement= (CPListElement) elements.get(i); entries[i]= currElement.getClasspathEntry(); } return entries; } // -------- evaluate default settings -------- private List getDefaultClassPath(IJavaProject jproj) { List list= new ArrayList(); IResource srcFolder; if (JavaBasePreferencePage.useSrcAndBinFolders()) { srcFolder= jproj.getProject().getFolder("src"); //$NON-NLS-1$ } else { srcFolder= jproj.getProject(); } list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder)); IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE); IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE); IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE); CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false); list.add(elem); return list; } private IPath getDefaultBuildPath(IJavaProject jproj) { if (JavaBasePreferencePage.useSrcAndBinFolders()) { return jproj.getProject().getFullPath().append("bin"); //$NON-NLS-1$ } else { return jproj.getProject().getFullPath(); } } private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { buildPathChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { buildPathDialogFieldChanged(field); } } private void buildPathChangeControlPressed(DialogField field) { if (field == fBuildPathDialogField) { IContainer container= chooseContainer(); if (container != null) { fBuildPathDialogField.setText(container.getFullPath().toString()); } } } private void buildPathDialogFieldChanged(DialogField field) { if (field == fClassPathList) { updateClassPathStatus(); updateBuildPathStatus(); } else if (field == fBuildPathDialogField) { updateBuildPathStatus(); } doStatusLineUpdate(); } // -------- verification ------------------------------- private void doStatusLineUpdate() { IStatus res= findMostSevereStatus(); fContext.statusChanged(res); } private IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus); } /** * Validates the build path. */ private void updateClassPathStatus() { fClassPathStatus.setOK(); List elements= fClassPathList.getElements(); boolean entryMissing= false; IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); boolean isChecked= fClassPathList.isChecked(currElement); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!isChecked) { fClassPathList.setCheckedWithoutUpdate(currElement, true); } } else { currElement.setExported(isChecked); } entries[i]= currElement.getClasspathEntry(); entryMissing= entryMissing || currElement.isMissing(); } if (entryMissing) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$ } if (fCurrJProject.hasClasspathCycle(entries)) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$ } } /** * Validates output location & build path. */ private void updateBuildPathStatus() { fOutputLocationPath= null; String text= fBuildPathDialogField.getText(); if ("".equals(text)) { //$NON-NLS-1$ fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$ return; } IPath path= getOutputLocation(); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { // if exists, must be a folder or project if (res.getType() == IResource.FILE) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$ return; } } else { // allows the build path to be in a different project, but must exists and be open IPath projPath= path.uptoSegment(1); if (!projPath.equals(fCurrJProject.getProject().getFullPath())) { IProject proj= (IProject)fWorkspaceRoot.findMember(projPath); if (proj == null || !proj.isOpen()) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.BuildPathProjNotExists")); //$NON-NLS-1$ return; } } } fOutputLocationPath= path; List elements= fClassPathList.getElements(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); entries[i]= currElement.getClasspathEntry(); } IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path); if (!status.isOK()) { fBuildPathStatus.setError(status.getMessage()); return; } fBuildPathStatus.setOK(); } // -------- creation ------------------------------- /** * Creates a runnable that sets the configured build paths. */ public IRunnableWithProgress getRunnable() { final List classPathEntries= fClassPathList.getElements(); final IPath path= getOutputLocation(); return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 12); //$NON-NLS-1$ try { createJavaProject(classPathEntries, path, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; } /** * Creates the Java project and sets the configured build path and output location. * If the project already exists only build paths are updated. */ private void createJavaProject(List classPathEntries, IPath buildPath, IProgressMonitor monitor) throws CoreException { IProject project= fCurrJProject.getProject(); if (!project.exists()) { project.create(null); } if (!project.isOpen()) { project.open(null); } // create java nature if (!project.hasNature(JavaCore.NATURE_ID)) { addNatureToProject(project, JavaCore.NATURE_ID, null); } monitor.worked(1); String[] prevRequiredProjects= fCurrJProject.getRequiredProjectNames(); // create and set the output path first if (!fWorkspaceRoot.exists(buildPath)) { IFolder folder= fWorkspaceRoot.getFolder(buildPath); CoreUtility.createFolder(folder, true, true, null); } monitor.worked(1); fCurrJProject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 3)); int nEntries= classPathEntries.size(); IClasspathEntry[] classpath= new IClasspathEntry[nEntries]; // create and set the class path for (int i= 0; i < nEntries; i++) { CPListElement entry= ((CPListElement)classPathEntries.get(i)); IResource res= entry.getResource(); if ((res instanceof IFolder) && !res.exists()) { CoreUtility.createFolder((IFolder)res, true, true, null); } classpath[i]= entry.getClasspathEntry(); } monitor.worked(1); fCurrJProject.setRawClasspath(classpath, new SubProgressMonitor(monitor, 5)); } /** * Adds a nature to a project */ private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException { IProjectDescription description = proj.getDescription(); String[] prevNatures= description.getNatureIds(); String[] newNatures= new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length]= natureId; description.setNatureIds(newNatures); proj.setDescription(description, monitor); } // ---------- util method ------------ private IContainer chooseContainer() { Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); IProject[] allProjects= fWorkspaceRoot.getProjects(); ArrayList rejectedElements= new ArrayList(allProjects.length); IProject currProject= fCurrJProject.getProject(); for (int i= 0; i < allProjects.length; i++) { if (!allProjects[i].equals(currProject)) { rejectedElements.add(allProjects[i]); } } ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSelection= null; if (fOutputLocationPath != null) { initSelection= fWorkspaceRoot.findMember(fOutputLocationPath); } ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$ dialog.setValidator(validator); dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSelection); if (dialog.open() == dialog.OK) { return (IContainer)dialog.getFirstResult(); } return null; } // -------- tab switching ---------- private void tabChanged(Widget widget) { if (widget instanceof TabItem) { BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData(); if (fCurrPage != null) { List selection= fCurrPage.getSelection(); if (!selection.isEmpty()) { newPage.setSelection(selection); } } fCurrPage= newPage; } } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/ChooseVariableDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; public class ChooseVariableDialog extends StatusDialog implements IStatusChangeListener, IDoubleClickListener { private VariableBlock fVariableBlock; public ChooseVariableDialog(Shell parent, String lastVariableSelection) { super(parent); setTitle(NewWizardMessages.getString("ChooseVariableDialog.variabledialog.title")); //$NON-NLS-1$ fVariableBlock= new VariableBlock(this, true, lastVariableSelection); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); fVariableBlock.createContents(composite); fVariableBlock.addDoubleClickListener(this); return composite; } protected void okPressed() { fVariableBlock.performOk(); super.okPressed(); } public String getSelectedVariable() { return fVariableBlock.getSelectedVariable(); } /* * @see IStatusChangeListener#statusChanged(IStatus) */ public void statusChanged(IStatus status) { updateStatus(status); } /* * @see IDoubleClickListener#doubleClick(DoubleClickEvent) */ public void doubleClick(DoubleClickEvent event) { if (getStatus().isOK()) { okPressed(); } } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.IUIConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class LibrariesWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; private IJavaProject fCurrJProject; private ListDialogField fLibrariesList; private IWorkspaceRoot fWorkspaceRoot; private IDialogSettings fDialogSettings; private Control fSWTControl; public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) { fClassPathList= classPathList; fWorkspaceRoot= root; fSWTControl= null; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addnew.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addexisting.button"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$ /* 3 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$ /* 5 */ null, /* 6 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.setsource.button"), //$NON-NLS-1$ /* 7 */ null, /* 8 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.remove.button") //$NON-NLS-1$ }; LibrariesAdapter adapter= new LibrariesAdapter(); fLibrariesList= new ListDialogField(adapter, buttonLabels, new CPListLabelProvider()); fLibrariesList.setDialogFieldListener(adapter); fLibrariesList.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.libraries.label")); //$NON-NLS-1$ fLibrariesList.setRemoveButtonIndex(8); //$NON-NLS-1$ fLibrariesList.enableButton(6, false); } public void init(IJavaProject jproject) { fCurrJProject= jproject; updateLibrariesList(); } private void updateLibrariesList() { List cpelements= fClassPathList.getElements(); List libelements= new ArrayList(cpelements.size()); int nElements= cpelements.size(); for (int i= 0; i < nElements; i++) { CPListElement cpe= (CPListElement)cpelements.get(i); int kind= cpe.getEntryKind(); if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) { libelements.add(cpe); } } fLibrariesList.setElements(libelements); } // -------- ui creation public Control getControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true, 0, 0, SWT.DEFAULT, SWT.DEFAULT); int buttonBarWidth= SWTUtil.convertWidthInCharsToPixels(24, composite); fLibrariesList.setButtonsMinWidth(buttonBarWidth); fLibrariesList.getTableViewer().setSorter(new CPListElementSorter()); fSWTControl= composite; return composite; } private Shell getShell() { if (fSWTControl != null) { return fSWTControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private class LibrariesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { libaryPageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) { libaryPageSelectionChanged(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { libaryPageDialogFieldChanged(field); } } private void libaryPageCustomButtonPressed(DialogField field, int index) { CPListElement[] libentries= null; switch (index) { case 0: /* add new */ libentries= createNewClassContainer(); break; case 1: /* add existing */ libentries= chooseClassContainers(); break; case 2: /* add jar */ libentries= chooseJarFiles(); break; case 3: /* add external jar */ libentries= chooseExtJarFiles(); break; case 4: /* add variable */ libentries= chooseVariableEntries(); break; case 6: /* set source attachment */ List selElements= fLibrariesList.getSelectedElements(); CPListElement selElement= (CPListElement) selElements.get(0); SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), selElement.getClasspathEntry()); if (dialog.open() == dialog.OK) { selElement.setSourceAttachment(dialog.getSourceAttachmentPath(), dialog.getSourceAttachmentRootPath()); fLibrariesList.refresh(); fClassPathList.refresh(); } break; } if (libentries != null) { int nElementsChosen= libentries.length; // remove duplicates List cplist= fLibrariesList.getElements(); List elementsToAdd= new ArrayList(nElementsChosen); for (int i= 0; i < nElementsChosen; i++) { CPListElement curr= libentries[i]; if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) { elementsToAdd.add(curr); addAttachmentsFromExistingLibs(curr); } } fLibrariesList.addElements(elementsToAdd); fLibrariesList.postSetSelection(new StructuredSelection(libentries)); } } private void libaryPageSelectionChanged(DialogField field) { List selElements= fLibrariesList.getSelectedElements(); fLibrariesList.enableButton(6, canDoSourceAttachment(selElements)); } private void libaryPageDialogFieldChanged(DialogField field) { if (fCurrJProject != null) { // already initialized updateClasspathList(); } } private boolean canDoSourceAttachment(List selElements) { if (selElements != null && selElements.size() == 1) { CPListElement elem= (CPListElement) selElements.get(0); return (!(elem.getResource() instanceof IFolder)); } return false; } private void updateClasspathList() { List projelements= fLibrariesList.getElements(); boolean remove= false; List cpelements= fClassPathList.getElements(); // backwards, as entries will be deleted for (int i= cpelements.size() - 1; i >= 0; i--) { CPListElement cpe= (CPListElement)cpelements.get(i); int kind= cpe.getEntryKind(); if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) { if (!projelements.remove(cpe)) { cpelements.remove(i); remove= true; } } } for (int i= 0; i < projelements.size(); i++) { cpelements.add(projelements.get(i)); } if (remove || (projelements.size() > 0)) { fClassPathList.setElements(cpelements); } } private CPListElement[] createNewClassContainer() { String title= NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.title"); //$NON-NLS-1$ IProject currProject= fCurrJProject.getProject(); NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers()); IPath projpath= currProject.getFullPath(); dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$ int ret= dialog.open(); if (ret == dialog.OK) { IFolder folder= dialog.getFolder(); return new CPListElement[] { newCPLibraryElement(folder) }; } return null; } private CPListElement[] chooseClassContainers() { Class[] acceptedClasses= new Class[] { IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); acceptedClasses= new Class[] { IProject.class, IFolder.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource) elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private CPListElement[] chooseJarFiles() { Class[] acceptedClasses= new Class[] { IFile.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource)elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private IContainer[] getUsedContainers() { ArrayList res= new ArrayList(); if (fCurrJProject.exists()) { try { IPath outputLocation= fCurrJProject.getOutputLocation(); if (outputLocation != null) { IResource resource= fWorkspaceRoot.findMember(outputLocation); if (resource instanceof IContainer) { res.add(resource); } } } catch (JavaModelException e) { // ignore it here, just log JavaPlugin.log(e.getStatus()); } } List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IContainer) { res.add(resource); } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } private IFile[] getUsedJARFiles() { List res= new ArrayList(); List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IFile) { res.add(resource); } } return (IFile[]) res.toArray(new IFile[res.size()]); } private CPListElement newCPLibraryElement(IResource res) { return new CPListElement(IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res); }; private CPListElement[] chooseExtJarFiles() { String lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR); if (lastUsedPath == null) { lastUsedPath= ""; //$NON-NLS-1$ } FileDialog dialog= new FileDialog(getShell(), SWT.MULTI); dialog.setText(NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(lastUsedPath); String res= dialog.open(); if (res == null) { return null; } String[] fileNames= dialog.getFileNames(); int nChosen= fileNames.length; IPath filterPath= new Path(dialog.getFilterPath()); CPListElement[] elems= new CPListElement[nChosen]; for (int i= 0; i < nChosen; i++) { IPath path= filterPath.append(fileNames[i]).makeAbsolute(); elems[i]= new CPListElement(IClasspathEntry.CPE_LIBRARY, path, null); } fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString()); return elems; } private CPListElement[] chooseVariableEntries() { ArrayList existingPaths= new ArrayList(); for (int i= 0; i < fLibrariesList.getSize(); i++) { CPListElement elem= (CPListElement) fLibrariesList.getElement(i); if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { existingPaths.add(elem.getPath()); } } VariableSelectionDialog dialog= new VariableSelectionDialog(getShell(), existingPaths); if (dialog.open() == dialog.OK) { IPath path= dialog.getVariable(); CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, path, null); IPath resolvedPath= JavaCore.getResolvedVariablePath(path); elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().isFile()); return new CPListElement[] { elem }; } return null; } private void addAttachmentsFromExistingLibs(CPListElement elem) { try { IJavaModel jmodel= fCurrJProject.getJavaModel(); IJavaProject[] jprojects= jmodel.getJavaProjects(); for (int i= 0; i < jprojects.length; i++) { IJavaProject curr= jprojects[i]; if (!curr.equals(fCurrJProject)) { IClasspathEntry[] entries= curr.getRawClasspath(); for (int k= 0; k < entries.length; k++) { IClasspathEntry entry= entries[k]; if (entry.getEntryKind() == elem.getEntryKind() && entry.getPath().equals(elem.getPath())) { IPath attachPath= entry.getSourceAttachmentPath(); if (attachPath != null && !attachPath.isEmpty()) { elem.setSourceAttachment(attachPath, entry.getSourceAttachmentRootPath()); return; } } } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } // a dialog to set the source attachment properties private class VariableSelectionDialog extends StatusDialog implements IStatusChangeListener { private VariableSelectionBlock fVariableSelectionBlock; public VariableSelectionDialog(Shell parent, List existingPaths) { super(parent); setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.title")); //$NON-NLS-1$ String initVar= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTVARIABLE); fVariableSelectionBlock= new VariableSelectionBlock(this, existingPaths, null, initVar, false); } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, new Object[] { IJavaHelpContextIds.VARIABLE_SELECTION_DIALOG }); } /* * @see StatusDialog#createDialogArea() */ protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Label message= new Label(composite, SWT.WRAP); message.setText(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.message")); //$NON-NLS-1$ message.setLayoutData(new GridData()); Control inner= fVariableSelectionBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } /* * @see Dialog#okPressed() */ protected void okPressed() { fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTVARIABLE, getVariable().segment(0)); super.okPressed(); } /* * @see IStatusChangeListener#statusChanged() */ public void statusChanged(IStatus status) { updateStatus(status); } public IPath getVariable() { return fVariableSelectionBlock.getVariablePath(); } } // a dialog to set the source attachment properties private class SourceAttachmentDialog extends StatusDialog implements IStatusChangeListener { private SourceAttachmentBlock fSourceAttachmentBlock; public SourceAttachmentDialog(Shell parent, IClasspathEntry entry) { super(parent); setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.SourceAttachmentDialog.title", entry.getPath().toString())); //$NON-NLS-1$ fSourceAttachmentBlock= new SourceAttachmentBlock(fWorkspaceRoot, this, entry); } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, new Object[] { IJavaHelpContextIds.SOURCE_ATTACHMENT_DIALOG }); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Control inner= fSourceAttachmentBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } public void statusChanged(IStatus status) { updateStatus(status); } public IPath getSourceAttachmentPath() { return fSourceAttachmentBlock.getSourceAttachmentPath(); } public IPath getSourceAttachmentRootPath() { return fSourceAttachmentBlock.getSourceAttachmentRootPath(); } } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { return fLibrariesList.getSelectedElements(); } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { for (int i= selElements.size()-1; i >= 0; i--) { CPListElement curr= (CPListElement) selElements.get(i); int kind= curr.getEntryKind(); if (kind != IClasspathEntry.CPE_LIBRARY && kind != IClasspathEntry.CPE_VARIABLE) { selElements.remove(i); } } fLibrariesList.selectElements(new StructuredSelection(selElements)); } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.core.resources.IProject; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class ProjectsWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; private IJavaProject fCurrJProject; private CheckedListDialogField fProjectsList; public ProjectsWorkbookPage(ListDialogField classPathList) { fClassPathList= classPathList; ProjectsListListener listener= new ProjectsListListener(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("ProjectsWorkbookPage.projects.checkall.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("ProjectsWorkbookPage.projects.uncheckall.button") //$NON-NLS-1$ }; fProjectsList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fProjectsList.setDialogFieldListener(listener); fProjectsList.setLabelText(NewWizardMessages.getString("ProjectsWorkbookPage.projects.label")); //$NON-NLS-1$ fProjectsList.setCheckAllButtonIndex(0); fProjectsList.setUncheckAllButtonIndex(1); } public void init(IJavaProject jproject) { updateProjectsList(jproject); } private void updateProjectsList(IJavaProject currJProject) { try { IJavaModel jmodel= currJProject.getJavaModel(); IJavaProject[] jprojects= jmodel.getJavaProjects(); List projects= new ArrayList(jprojects.length); // a vector remembering all projects that dont have to be added anymore List existingProjects= new ArrayList(jprojects.length); existingProjects.add(currJProject.getProject()); final List checkedProjects= new ArrayList(jprojects.length); // add the projects-cpentries that are already on the class path List cpelements= fClassPathList.getElements(); for (int i= cpelements.size() - 1 ; i >= 0; i--) { CPListElement cpelem= (CPListElement)cpelements.get(i); if (cpelem.getEntryKind() == IClasspathEntry.CPE_PROJECT) { existingProjects.add(cpelem.getResource()); projects.add(cpelem); checkedProjects.add(cpelem); } } for (int i= 0; i < jprojects.length; i++) { IProject proj= jprojects[i].getProject(); if (!existingProjects.contains(proj)) { projects.add(new CPListElement(IClasspathEntry.CPE_PROJECT, proj.getFullPath(), proj)); } } fProjectsList.setElements(projects); fProjectsList.setCheckedElements(checkedProjects); } catch (JavaModelException e) { // no solution exists or other problems: create an empty list fProjectsList.setElements(new ArrayList(5)); } fCurrJProject= currJProject; } // -------- UI creation --------- public Control getControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fProjectsList }, true, 0, 0, SWT.DEFAULT, SWT.DEFAULT); int buttonBarWidth= SWTUtil.convertWidthInCharsToPixels(24, composite); fProjectsList.setButtonsMinWidth(buttonBarWidth); fProjectsList.getTableViewer().setSorter(new CPListElementSorter()); return composite; } private class ProjectsListListener implements IDialogFieldListener { // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { if (fCurrJProject != null) { // already initialized updateClasspathList(); } } } private void updateClasspathList() { List projelements= fProjectsList.getCheckedElements(); boolean remove= false; List cpelements= fClassPathList.getElements(); // backwards, as entries will be deleted for (int i= cpelements.size() -1; i >= 0 ; i--) { CPListElement cpe= (CPListElement)cpelements.get(i); if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) { if (!projelements.remove(cpe)) { cpelements.remove(i); remove= true; } } } for (int i= 0; i < projelements.size(); i++) { cpelements.add(projelements.get(i)); } if (remove || (projelements.size() > 0)) { fClassPathList.setElements(cpelements); } } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { return fProjectsList.getSelectedElements(); } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { filterSelection(selElements, IClasspathEntry.CPE_PROJECT); fProjectsList.selectElements(new StructuredSelection(selElements)); } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class SourceContainerWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; private IJavaProject fCurrJProject; private IPath fProjPath; private Control fSWTControl; private IWorkspaceRoot fWorkspaceRoot; private SelectionButtonDialogField fProjectRadioButton; private SelectionButtonDialogField fFolderRadioButton; private ListDialogField fFoldersList; private CPListElement fProjectCPEntry; private StringDialogField fOutputLocationField; private boolean fIsProjSelected; public SourceContainerWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList, StringDialogField outputLocationField, boolean isNewProject) { fWorkspaceRoot= root; fClassPathList= classPathList; fProjectCPEntry= null; fOutputLocationField= outputLocationField; fSWTControl= null; SourceContainerAdapter adapter= new SourceContainerAdapter(); fProjectRadioButton= new SelectionButtonDialogField(SWT.RADIO); fProjectRadioButton.setDialogFieldListener(adapter); fProjectRadioButton.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.rb1.label")); //$NON-NLS-1$ fFolderRadioButton= new SelectionButtonDialogField(SWT.RADIO); fFolderRadioButton.setDialogFieldListener(adapter); fFolderRadioButton.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.rb2.label")); //$NON-NLS-1$ String[] buttonLabels; int removeIndex; if (isNewProject) { buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.addnew.button"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$ }; removeIndex= 2; } else { buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.addnew.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.addnew.addexisting.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$ }; removeIndex= 3; } fFoldersList= new ListDialogField(adapter, buttonLabels, new CPListLabelProvider()); fFoldersList.setDialogFieldListener(adapter); fFoldersList.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.label")); //$NON-NLS-1$ fFoldersList.setRemoveButtonIndex(removeIndex); fFolderRadioButton.attachDialogField(fFoldersList); } public void init(IJavaProject jproject) { fCurrJProject= jproject; fProjPath= fCurrJProject.getProject().getFullPath(); updateFoldersList(); } private void updateFoldersList() { fIsProjSelected= false; List srcelements= new ArrayList(fClassPathList.getSize()); List cpelements= fClassPathList.getElements(); for (int i= 0; i < cpelements.size(); i++) { CPListElement cpe= (CPListElement)cpelements.get(i); if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (fProjPath.equals(cpe.getPath())) { srcelements.clear(); // remember the entry to ensure a unique CPListElement for the project-cpentry fProjectCPEntry= cpe; fIsProjSelected= true; break; } else { srcelements.add(cpe); } } } fFoldersList.setElements(srcelements); // fix for 1G47IYV: ITPJUI:WINNT - Both radio buttons get selected in Project properties fFolderRadioButton.setSelection(!fIsProjSelected); fProjectRadioButton.setSelection(fIsProjSelected); } public Control getControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); layout.numColumns= 2; composite.setLayout(layout); fProjectRadioButton.doFillIntoGrid(composite, 2); fFolderRadioButton.doFillIntoGrid(composite, 2); Control control= fFoldersList.getListControl(composite); MGridData gd= new MGridData(MGridData.FILL_BOTH); gd.horizontalIndent= SWTUtil.convertWidthInCharsToPixels(2, composite); gd.widthHint= SWTUtil.convertWidthInCharsToPixels(75, composite); gd.heightHint= SWTUtil.convertWidthInCharsToPixels(15, composite); control.setLayoutData(gd); control= fFoldersList.getButtonBox(composite); gd= new MGridData(gd.VERTICAL_ALIGN_FILL + gd.HORIZONTAL_ALIGN_FILL); control.setLayoutData(gd); int buttonBarWidth= SWTUtil.convertWidthInCharsToPixels(24, composite); fFoldersList.setButtonsMinWidth(buttonBarWidth); fFoldersList.getTableViewer().setSorter(new CPListElementSorter()); fSWTControl= composite; return composite; } private Shell getShell() { if (fSWTControl != null) { return fSWTControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private class SourceContainerAdapter implements IListAdapter, IDialogFieldListener { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { sourcePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { sourcePageDialogFieldChanged(field); } } private void sourcePageCustomButtonPressed(DialogField field, int index) { if (field == fFoldersList) { List elementsToAdd= new ArrayList(10); switch (index) { case 0: /* add new */ CPListElement srcentry= createNewSourceContainer(); if (srcentry != null) { elementsToAdd.add(srcentry); } break; case 1: /* add existing */ CPListElement[] srcentries= chooseSourceContainers(); if (srcentries != null) { for (int i= 0; i < srcentries.length; i++) { elementsToAdd.add(srcentries[i]); } } break; } if (!elementsToAdd.isEmpty()) { fFoldersList.addElements(elementsToAdd); fFoldersList.postSetSelection(new StructuredSelection(elementsToAdd)); // if no source folders up to now if (fFoldersList.getSize() == elementsToAdd.size()) { askForChangingBuildPathDialog(); } } } } private void sourcePageDialogFieldChanged(DialogField field) { if (fCurrJProject == null) { // not initialized return; } if (field == fFolderRadioButton) { if (fFolderRadioButton.isSelected()) { fIsProjSelected= false; updateClasspathList(); if (fFoldersList.getSize() > 0) { askForChangingBuildPathDialog(); } } } else if (field == fProjectRadioButton) { if (fProjectRadioButton.isSelected()) { fIsProjSelected= true; updateClasspathList(); } } else if (field == fFoldersList) { updateClasspathList(); } } private void updateClasspathList() { List cpelements= fClassPathList.getElements(); List srcelements; if (fIsProjSelected) { srcelements= new ArrayList(1); if (fProjectCPEntry == null) { // never initialized before: create a new one fProjectCPEntry= newCPSourceElement(fCurrJProject.getProject()); } srcelements.add(fProjectCPEntry); } else { srcelements= fFoldersList.getElements(); } boolean changeDone= false; // backwards, as entries will be deleted for (int i= cpelements.size() - 1; i >= 0 ; i--) { CPListElement cpe= (CPListElement)cpelements.get(i); if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) { // if it is a source folder, but not one of the accepted entries, remove it // at the same time, for the entries seen, remove them from the accepted list if (!srcelements.remove(cpe)) { cpelements.remove(i); changeDone= true; } } } for (int i= 0; i < srcelements.size(); i++) { cpelements.add(srcelements.get(i)); } if (changeDone || (srcelements.size() > 0)) { fClassPathList.setElements(cpelements); } } private CPListElement createNewSourceContainer() { IProject proj= fCurrJProject.getProject(); String title= NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.title"); //$NON-NLS-1$ NewContainerDialog dialog= new NewContainerDialog(getShell(), title, proj, getExistingContainers()); dialog.setMessage(NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.NewSourceFolderDialog.description", fProjPath.toString())); //$NON-NLS-1$ if (dialog.open() == dialog.OK) { IFolder folder= dialog.getFolder(); return newCPSourceElement(folder); } return null; } /** * Asks to change the output folder to 'proj/bin' when no source folders were existing */ private void askForChangingBuildPathDialog() { IPath outputFolder= new Path(fOutputLocationField.getText()); if (outputFolder.segmentCount() == 1) { IPath newPath= outputFolder.append("bin"); String title= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.message", newPath); //$NON-NLS-1$ if (MessageDialog.openQuestion(getShell(), title, message)) { fOutputLocationField.setText(newPath.toString()); } } } private CPListElement[] chooseSourceContainers() { Class[] acceptedClasses= new Class[] { IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true); acceptedClasses= new Class[] { IFolder.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getExistingContainers()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fCurrJProject.getProject()); if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource)elements[i]; res[i]= newCPSourceElement(elem); } return res; } return null; } private IContainer[] getExistingContainers() { List res= new ArrayList(); List cplist= fFoldersList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); IResource resource= elem.getResource(); if (resource instanceof IContainer) { // defensive code res.add(resource); } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } private CPListElement newCPSourceElement(IResource res) { Assert.isNotNull(res); return new CPListElement(IClasspathEntry.CPE_SOURCE, res.getFullPath(), res); } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { if (fIsProjSelected) { ArrayList list= new ArrayList(1); list.add(fProjectCPEntry); return list; } else { return fFoldersList.getSelectedElements(); } } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { if (!fIsProjSelected) { filterSelection(selElements, IClasspathEntry.CPE_SOURCE); fFoldersList.selectElements(new StructuredSelection(selElements)); } } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class VariableBlock { private ListDialogField fVariablesList; private StatusInfo fSelectionStatus; private IStatusChangeListener fContext; private boolean fUseAsSelectionDialog; private boolean fRemovingSelection= false; private String fSelectedVariable; private Control fControl; /** * Constructor for VariableBlock */ public VariableBlock(IStatusChangeListener context, boolean useAsSelectionDialog, String initSelection) { fContext= context; fUseAsSelectionDialog= useAsSelectionDialog; fSelectionStatus= new StatusInfo(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("VariableBlock.vars.add.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("VariableBlock.vars.edit.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("VariableBlock.vars.remove.button") //$NON-NLS-1$ }; VariablesAdapter adapter= new VariablesAdapter(); CPVariableElementLabelProvider labelProvider= new CPVariableElementLabelProvider(useAsSelectionDialog); fVariablesList= new ListDialogField(adapter, buttonLabels, labelProvider); fVariablesList.setDialogFieldListener(adapter); fVariablesList.setLabelText(NewWizardMessages.getString("VariableBlock.vars.label")); //$NON-NLS-1$ fVariablesList.setRemoveButtonIndex(3); fVariablesList.enableButton(1, false); CPVariableElement initSelectedElement= null; String[] reservedName= getReservedVariableNames(); ArrayList reserved= new ArrayList(reservedName.length); addAll(reservedName, reserved); String[] entries= JavaCore.getClasspathVariableNames(); ArrayList elements= new ArrayList(entries.length); for (int i= 0; i < entries.length; i++) { String name= entries[i]; CPVariableElement elem; IPath entryPath= JavaCore.getClasspathVariable(name); elem= new CPVariableElement(name, entryPath, reserved.contains(name)); elements.add(elem); if (name.equals(initSelection)) { initSelectedElement= elem; } } fVariablesList.setElements(elements); ISelection sel; if (initSelectedElement != null) { sel= new StructuredSelection(initSelectedElement); } else if (entries.length > 0) { sel= new StructuredSelection(fVariablesList.getElement(0)); } else { sel= StructuredSelection.EMPTY; } fVariablesList.selectElements(sel); } private String[] getReservedVariableNames() { return new String[] { JavaRuntime.JRELIB_VARIABLE, JavaRuntime.JRESRC_VARIABLE, JavaRuntime.JRESRCROOT_VARIABLE, }; } public Control createContents(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); int minimalWidth= SWTUtil.convertWidthInCharsToPixels(80, composite); int minimalHeight= SWTUtil.convertHeightInCharsToPixels(20, composite); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fVariablesList }, true, minimalWidth, minimalHeight, 0, 0); fVariablesList.getTableViewer().setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof CPVariableElement && e2 instanceof CPVariableElement) { return ((CPVariableElement)e1).getName().compareTo(((CPVariableElement)e2).getName()); } return super.compare(viewer, e1, e2); } }); fControl= composite; return composite; } public void addDoubleClickListener(IDoubleClickListener listener) { fVariablesList.getTableViewer().addDoubleClickListener(listener); } private Shell getShell() { if (fControl != null) { return fControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } public String getSelectedVariable() { return fSelectedVariable; } private class VariablesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { switch (index) { case 0: /* add */ editEntries(null); break; case 1: /* edit */ List selected= fVariablesList.getSelectedElements(); editEntries((CPVariableElement)selected.get(0)); break; } } public void selectionChanged(DialogField field) { doSelectionChanged(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { } } private boolean containsReserved(List selected) { for (int i= selected.size()-1; i >= 0; i--) { if (((CPVariableElement)selected.get(i)).isReserved()) { return true; } } return false; } private static void addAll(Object[] objs, Collection dest) { for (int i= 0; i < objs.length; i++) { dest.add(objs[i]); } } private void doSelectionChanged(DialogField field) { List selected= fVariablesList.getSelectedElements(); boolean isSingleSelected= selected.size() == 1; boolean containsReserved= containsReserved(selected); // edit fVariablesList.enableButton(1, isSingleSelected && !containsReserved); // remove button fVariablesList.enableButton(3, !containsReserved); fSelectedVariable= null; if (fUseAsSelectionDialog) { if (isSingleSelected) { fSelectionStatus.setOK(); fSelectedVariable= ((CPVariableElement)selected.get(0)).getName(); } else { fSelectionStatus.setError(""); //$NON-NLS-1$ } fContext.statusChanged(fSelectionStatus); } } private void editEntries(CPVariableElement entry) { List existingEntries= fVariablesList.getElements(); VariableCreationDialog dialog= new VariableCreationDialog(getShell(), entry, existingEntries); if (dialog.open() != dialog.OK) { return; } CPVariableElement newEntry= dialog.getClasspathElement(); if (entry == null) { fVariablesList.addElement(newEntry); entry= newEntry; } else { entry.setName(newEntry.getName()); entry.setPath(newEntry.getPath()); fVariablesList.refresh(); } fVariablesList.selectElements(new StructuredSelection(entry)); } public void performDefaults() { fVariablesList.removeAllElements(); String[] reservedName= getReservedVariableNames(); for (int i= 0; i < reservedName.length; i++) { CPVariableElement elem= new CPVariableElement(reservedName[i], null, true); elem.setReserved(true); fVariablesList.addElement(elem); } } public boolean performOk() { List toRemove= new ArrayList(); toRemove.addAll(Arrays.asList(JavaCore.getClasspathVariableNames())); // remove all unchanged List elements= fVariablesList.getElements(); for (int i= elements.size()-1; i >= 0; i--) { CPVariableElement curr= (CPVariableElement) elements.get(i); if (curr.isReserved()) { elements.remove(curr); } else { IPath path= curr.getPath(); IPath prevPath= JavaCore.getClasspathVariable(curr.getName()); if (prevPath != null && prevPath.equals(path)) { elements.remove(curr); } } toRemove.remove(curr.getName()); } int steps= elements.size() + toRemove.size(); if (steps > 0) { IRunnableWithProgress runnable= new VariableBlockRunnable(toRemove, elements); ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); try { dialog.run(true, true, runnable); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), NewWizardMessages.getString("VariableBlock.operation_errror.title"), NewWizardMessages.getString("VariableBlock.operation_errror.message")); return false; } catch (InterruptedException e) { return true; } } return true; } private class VariableBlockRunnable implements IRunnableWithProgress { private List fToRemove; private List fToChange; public VariableBlockRunnable(List toRemove, List toChange) { fToRemove= toRemove; fToChange= toChange; } /* * @see IRunnableWithProgress#run(IProgressMonitor) */ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int steps= fToChange.size() + fToRemove.size(); monitor.beginTask(NewWizardMessages.getString("VariableBlock.operation_desc"), steps); //$NON-NLS-1$ try { for (int i= 0; i < fToChange.size(); i++) { CPVariableElement curr= (CPVariableElement) fToChange.get(i); SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1); JavaCore.setClasspathVariable(curr.getName(), curr.getPath(), subMonitor); if (monitor.isCanceled()) { return; } } for (int i= 0; i < fToRemove.size(); i++) { SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1); JavaCore.removeClasspathVariable((String) fToRemove.get(i), subMonitor); if (monitor.isCanceled()) { return; } } } catch (JavaModelException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableSelectionBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; 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.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jdt.core.JavaCore; 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.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; 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; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class VariableSelectionBlock { private List fExistingPaths; private StringButtonDialogField fVariableField; private StringButtonDialogField fExtensionField; private CLabel fFullPath; private IStatus fVariableStatus; private IStatus fExistsStatus; private IStatus fExtensionStatus; private String fVariable; private IStatusChangeListener fContext; private boolean fIsEmptyAllowed; private String fLastVariableSelection; /** * Constructor for VariableSelectionBlock */ public VariableSelectionBlock(IStatusChangeListener context, List existingPaths, IPath varPath, String lastVarSelection, boolean emptyAllowed) { fContext= context; fExistingPaths= existingPaths; fIsEmptyAllowed= emptyAllowed; fLastVariableSelection= lastVarSelection; fVariableStatus= new StatusInfo(); fExistsStatus= new StatusInfo(); VariableSelectionAdapter adapter= new VariableSelectionAdapter(); fVariableField= new StringButtonDialogField(adapter); fVariableField.setDialogFieldListener(adapter); fVariableField.setLabelText(NewWizardMessages.getString("VariableSelectionBlock.variable.label")); //$NON-NLS-1$ fVariableField.setButtonLabel(NewWizardMessages.getString("VariableSelectionBlock.variable.button")); //$NON-NLS-1$ fExtensionField= new StringButtonDialogField(adapter); fExtensionField.setDialogFieldListener(adapter); fExtensionField.setLabelText(NewWizardMessages.getString("VariableSelectionBlock.extension.label")); //$NON-NLS-1$ fExtensionField.setButtonLabel(NewWizardMessages.getString("VariableSelectionBlock.extension.button")); //$NON-NLS-1$ if (varPath != null) { fVariableField.setText(varPath.segment(0)); fExtensionField.setText(varPath.removeFirstSegments(1).toString()); } else { fVariableField.setText(""); //$NON-NLS-1$ fExtensionField.setText(""); //$NON-NLS-1$ } updateFullTextField(); } public IPath getVariablePath() { if (fVariable != null) { return new Path(fVariable).append(fExtensionField.getText()); } return null; } public IPath getResolvedPath() { if (fVariable != null) { IPath entryPath= JavaCore.getClasspathVariable(fVariable); if (entryPath != null) { return entryPath.append(fExtensionField.getText()); } } return null; } public void setFocus(Display display) { fVariableField.postSetFocusOnDialogField(display); } public Control createControl(Composite parent) { int nColumns= 3; Composite inner= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, parent); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= nColumns; inner.setLayout(layout); int fieldWidthHint= SWTUtil.convertWidthInCharsToPixels(50, parent); fVariableField.doFillIntoGrid(inner, nColumns); LayoutUtil.setWidthHint(fVariableField.getTextControl(null), fieldWidthHint); fExtensionField.doFillIntoGrid(inner, nColumns); LayoutUtil.setWidthHint(fExtensionField.getTextControl(null), fieldWidthHint); Label label= new Label(inner, SWT.LEFT); label.setLayoutData(new MGridData()); label.setText(NewWizardMessages.getString("VariableSelectionBlock.fullpath.label")); //$NON-NLS-1$ fFullPath= new CLabel(inner, SWT.NONE); fFullPath.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(inner, nColumns - 2); updateFullTextField(); setFocus(parent.getDisplay()); return inner; } // -------- VariableSelectionAdapter -------- private class VariableSelectionAdapter implements IDialogFieldListener, IStringButtonAdapter { // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { doFieldUpdated(field); } // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { doChangeControlPressed(field); } } private void doChangeControlPressed(DialogField field) { if (field == fVariableField) { String variable= chooseVariable(); if (variable != null) { fVariableField.setText(variable); } } else if (field == fExtensionField) { IPath filePath= chooseExtJar(); if (filePath != null) { fExtensionField.setText(filePath.toString()); } } } private void doFieldUpdated(DialogField field) { if (field == fVariableField) { fVariableStatus= variableUpdated(); } else if (field == fExtensionField) { fExtensionStatus= extensionUpdated(); } fExistsStatus= getExistsStatus(); updateFullTextField(); fContext.statusChanged(StatusUtil.getMostSevere(new IStatus[] { fVariableStatus, fExtensionStatus, fExistsStatus })); } private IStatus variableUpdated() { fVariable= null; StatusInfo status= new StatusInfo(); String name= fVariableField.getText(); if (name.length() == 0) { if (!fIsEmptyAllowed) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.entername")); //$NON-NLS-1$ } else { fVariable= ""; //$NON-NLS-1$ } } else if (JavaCore.getClasspathVariable(name) == null) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.namenotexists")); //$NON-NLS-1$ } else { fVariable= name; } fExtensionField.enableButton(fVariable != null); return status; } private IStatus extensionUpdated() { StatusInfo status= new StatusInfo(); String extension= fExtensionField.getText(); if (extension.length() > 0 && !Path.ROOT.isValidPath(extension)) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.invalidextension")); //$NON-NLS-1$ } return status; } private IStatus getExistsStatus() { StatusInfo status= new StatusInfo(); IPath path= getResolvedPath(); if (path != null) { if (findPath(path)) { status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.pathexists")); //$NON-NLS-1$ } else if (!path.toFile().isFile()) { status.setWarning(NewWizardMessages.getString("VariableSelectionBlock.warning.pathnotexists")); //$NON-NLS-1$ } } else { status.setWarning(NewWizardMessages.getString("VariableSelectionBlock.warning.pathnotexists")); //$NON-NLS-1$ } return status; } private boolean findPath(IPath path) { for (int i= fExistingPaths.size() -1; i >=0; i--) { IPath curr= (IPath) fExistingPaths.get(i); if (curr.equals(path)) { return true; } } return false; } private void updateFullTextField() { if (fFullPath != null && !fFullPath.isDisposed()) { IPath resolvedPath= getResolvedPath(); if (resolvedPath != null) { fFullPath.setText(resolvedPath.toOSString()); } else { fFullPath.setText(""); //$NON-NLS-1$ } } } private Shell getShell() { if (fFullPath != null) { return fFullPath.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private IPath chooseExtJar() { String lastUsedPath= ""; //$NON-NLS-1$ IPath entryPath= getResolvedPath(); if (entryPath != null) { if (ArchiveFileFilter.isArchivePath(entryPath)) { lastUsedPath= entryPath.removeLastSegments(1).toOSString(); } else { lastUsedPath= entryPath.toOSString(); } } FileDialog dialog= new FileDialog(getShell(), SWT.SINGLE); dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(lastUsedPath); dialog.setText(NewWizardMessages.getString("VariableSelectionBlock.ExtJarDialog.title")); //$NON-NLS-1$ String res= dialog.open(); if (res == null) { return null; } IPath resPath= new Path(res).makeAbsolute(); IPath varPath= JavaCore.getClasspathVariable(fVariable); if (!varPath.isPrefixOf(resPath)) { return new Path(resPath.lastSegment()); } else { return resPath.removeFirstSegments(varPath.segmentCount()).setDevice(null); } } private String chooseVariable() { String selecteVariable= (fVariable != null) ? fVariable : fLastVariableSelection; ChooseVariableDialog dialog= new ChooseVariableDialog(getShell(), selecteVariable); if (dialog.open() == dialog.OK) { return dialog.getSelectedVariable(); } return null; } }
6,196
Bug 6196 Last item selected by default in variable selection dialog
Build 20011120 - go to add a classpath variable - Browse for var name - it selects the last item by default Normally the default selection is the first item. This seems picky, but it's actually fairly annoying when using keyboard navigation for the default selection to be in the wrong place. (particularly when the one I always go for is ECLIPSE_HOME, which is always the first item <g>).
verified fixed
e26dfad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-23T15:53:36Z"
"2001-11-21T22:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; 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.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ColumnWeightData; 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.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; /** * A list with a button bar. * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. * List model is independend of widget creation. * DialogFields controls are: Label, List and Composite containing buttons. */ public class ListDialogField extends DialogField { protected TableViewer fTable; protected ILabelProvider fLabelProvider; protected ListViewerAdapter fListViewerAdapter; protected List fElements; protected String[] fButtonLabels; private Button[] fButtonControls; private boolean[] fButtonsEnabled; private int fRemoveButtonIndex; private int fUpButtonIndex; private int fDownButtonIndex; private Label fLastSeparator; private Table fTableControl; private Composite fButtonsControl; private ISelection fSelectionWhenEnabled; private TableColumn fTableColumn; private IListAdapter fListAdapter; private Object fParentElement; /** * Creates the <code>ListDialogField</code>. * @param adapter A listener for button invocation, selection changes. * @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and * marks a separator. * @param lprovider The label provider to render the table entries */ public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) { super(); fListAdapter= adapter; fLabelProvider= lprovider; fListViewerAdapter= new ListViewerAdapter(); fParentElement= this; fElements= new ArrayList(10); fButtonLabels= buttonLabels; if (fButtonLabels != null) { int nButtons= fButtonLabels.length; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsEnabled[i]= true; } } fTable= null; fTableControl= null; fButtonsControl= null; fRemoveButtonIndex= -1; fUpButtonIndex= -1; fDownButtonIndex= -1; } /** * Sets the index of the 'remove' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'remove' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); fRemoveButtonIndex= removeButtonIndex; } /** * Sets the index of the 'up' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'up' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); fUpButtonIndex= upButtonIndex; } /** * Sets the index of the 'down' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'down' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); fDownButtonIndex= downButtonIndex; } // ------ adapter communication private void buttonPressed(int index) { if (!managedButtonPressed(index)) { fListAdapter.customButtonPressed(this, index); } } /** * Checks if the button pressed is handled internally * @return Returns true if button has been handled. */ protected boolean managedButtonPressed(int index) { if (index == fRemoveButtonIndex) { remove(); } else if (index == fUpButtonIndex) { up(); } else if (index == fDownButtonIndex) { down(); } else { return false; } return true; } // ------ layout helpers /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); Label label= getLabelControl(parent); MGridData gd= gridDataForLabel(1); gd.verticalAlignment= gd.BEGINNING; label.setLayoutData(gd); Control list= getListControl(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= true; gd.grabColumn= 0; gd.horizontalSpan= nColumns - 2; gd.widthHint= SWTUtil.convertWidthInCharsToPixels(40, list); gd.heightHint= SWTUtil.convertHeightInCharsToPixels(6, list); list.setLayoutData(gd); Composite buttons= getButtonBox(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= false; gd.horizontalSpan= 1; buttons.setLayoutData(gd); return new Control[] { label, list, buttons }; } /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { return 3; } /** * Sets the minimal width of the buttons. Must be called after widget creation. */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { ((MGridData)fLastSeparator.getLayoutData()).widthHint= minWidth; } } // ------ ui creation /** * Returns the list control. When called the first time, the control will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Control getListControl(Composite parent) { if (fTableControl == null) { assertCompositeNotNull(parent); fTable= createTableViewer(parent); fTable.setContentProvider(fListViewerAdapter); fTable.setLabelProvider(fLabelProvider); fTable.addSelectionChangedListener(fListViewerAdapter); fTableControl= (Table)fTable.getControl(); // Add a table column. TableLayout tableLayout= new TableLayout(); tableLayout.addColumnData(new ColumnWeightData(100)); fTableColumn= new TableColumn(fTableControl, SWT.NONE); fTableColumn.setResizable(false); fTableControl.setLayout(tableLayout); fTable.setInput(fParentElement); fTableControl.setEnabled(isEnabled()); if (fSelectionWhenEnabled != null) { postSetSelection(fSelectionWhenEnabled); } fTableColumn.getDisplay().asyncExec(new Runnable() { public void run() { if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } } }); } return fTableControl; } /** * Returns the internally used table viewer. */ public TableViewer getTableViewer() { return fTable; } /* * Subclasses may override to specify a different style. */ protected int getListStyle(){ return SWT.BORDER + SWT.MULTI + SWT.H_SCROLL + SWT.V_SCROLL; } protected TableViewer createTableViewer(Composite parent) { Table table= new Table(parent, getListStyle()); return new TableViewer(table); } protected Button createButton(Composite parent, String label, SelectionListener listener) { Button button= new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(listener); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.BEGINNING; gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); return button; } private Label createSeparator(Composite parent) { Label separator= new Label(parent, SWT.NONE); separator.setVisible(false); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.verticalAlignment= gd.BEGINNING; gd.heightHint= 4; separator.setLayoutData(gd); return separator; } /** * Returns the composite containing the buttons. When called the first time, the control * will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; Composite contents= new Composite(parent, SWT.NULL); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; contents.setLayout(layout); if (fButtonLabels != null) { fButtonControls= new Button[fButtonLabels.length]; for (int i= 0; i < fButtonLabels.length; i++) { String currLabel= fButtonLabels[i]; if (currLabel != null) { fButtonControls[i]= createButton(contents, currLabel, listener); fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); } else { fButtonControls[i]= null; createSeparator(contents); } } } fLastSeparator= createSeparator(contents); updateButtonState(); fButtonsControl= contents; } return fButtonsControl; } private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { for (int i= 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; } } } } // ------ enable / disable management /* * @see DialogField#dialogFieldChanged */ public void dialogFieldChanged() { super.dialogFieldChanged(); if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } updateButtonState(); } private Button getButton(int index) { if (fButtonControls != null && index >= 0 && index < fButtonControls.length) { return fButtonControls[index]; } return null; } /* * Updates the enable state of the all buttons */ protected void updateButtonState() { if (fButtonControls != null) { ISelection sel= fTable.getSelection(); for (int i= 0; i < fButtonControls.length; i++) { Button button= fButtonControls[i]; if (isOkToUse(button)) { boolean extraState= getManagedButtonState(sel, i); button.setEnabled(isEnabled() && extraState && fButtonsEnabled[i]); } } } } protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fRemoveButtonIndex) { return !sel.isEmpty(); } else if (index == fUpButtonIndex) { return !sel.isEmpty() && canMoveUp(); } else if (index == fDownButtonIndex) { return !sel.isEmpty() && canMoveDown(); } return true; } /* * @see DialogField#updateEnableState */ protected void updateEnableState() { super.updateEnableState(); boolean enabled= isEnabled(); if (isOkToUse(fTableControl)) { if (!enabled) { fSelectionWhenEnabled= fTable.getSelection(); selectElements(null); } else { selectElements(fSelectionWhenEnabled); fSelectionWhenEnabled= null; } fTableControl.setEnabled(enabled); } updateButtonState(); } /** * Sets a button enabled or disabled. */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { fButtonsEnabled[index]= enable; updateButtonState(); } } // ------ model access /** * Sets the elements shown in the list. */ public void setElements(List elements) { fElements= new ArrayList(elements); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } /** * Gets the elements shown in the list. * The list returned is a copy, so it can be modified by the user. */ public List getElements() { return new ArrayList(fElements); } /** * Gets the elements shown at the given index. */ public Object getElement(int index) { return fElements.get(index); } /** * Replace an element. */ public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException { int idx= fElements.indexOf(oldElement); if (idx != -1) { if (oldElement.equals(newElement) || fElements.contains(newElement)) { return; } fElements.set(idx, newElement); if (fTable != null) { List selected= getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } fTable.refresh(); fTable.setSelection(new StructuredSelection(selected)); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Adds an element at the end of the list. */ public void addElement(Object element) { if (fElements.contains(element)) { return; } fElements.add(element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds elements at the end of the list. */ public void addElements(List elements) { int nElements= elements.size(); if (nElements > 0) { // filter duplicated ArrayList elementsToAdd= new ArrayList(nElements); for (int i= 0; i < nElements; i++) { Object elem= elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); } } fElements.addAll(elementsToAdd); if (fTable != null) { fTable.add(elementsToAdd.toArray()); } dialogFieldChanged(); } } /** * Adds an element at a position. */ public void insertElementAt(Object element, int index) { if (fElements.contains(element)) { return; } fElements.add(index, element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds an element at a position. */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } } /** * Removes an element from the list. */ public void removeElement(Object element) throws IllegalArgumentException { if (fElements.remove(element)) { if (fTable != null) { fTable.remove(element); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Removes elements from the list. */ public void removeElements(List elements) { if (elements.size() > 0) { fElements.removeAll(elements); if (fTable != null) { fTable.remove(elements.toArray()); } dialogFieldChanged(); } } /** * Gets the number of elements */ public int getSize() { return fElements.size(); } public void selectElements(ISelection selection) { fSelectionWhenEnabled= selection; if (fTable != null) { fTable.setSelection(selection); } } public void postSetSelection(final ISelection selection) { if (isOkToUse(fTableControl)) { Display d= fTableControl.getDisplay(); d.asyncExec(new Runnable() { public void run() { if (isOkToUse(fTableControl)) { selectElements(selection); } } }); } } /** * Refreshes the table. */ public void refresh() { fTable.refresh(); } // ------- list maintenance private List moveUp(List elements, List move) { int nElements= elements.size(); List res= new ArrayList(nElements); Object floating= null; for (int i= 0; i < nElements; i++) { Object curr= elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } floating= curr; } } if (floating != null) { res.add(floating); } return res; } private void moveUp(List toMoveUp) { if (toMoveUp.size() > 0) { setElements(moveUp(fElements, toMoveUp)); fTable.reveal(toMoveUp.get(0)); } } private void moveDown(List toMoveDown) { if (toMoveDown.size() > 0) { setElements(reverse(moveUp(reverse(fElements), toMoveDown))); fTable.reveal(toMoveDown.get(toMoveDown.size() - 1)); } } private List reverse(List p) { List reverse= new ArrayList(p.size()); for (int i= p.size()-1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; } private void remove() { removeElements(getSelectedElements()); } private void up() { moveUp(getSelectedElements()); } private void down() { moveDown(getSelectedElements()); } private boolean canMoveUp() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); for (int i= 0; i < indc.length; i++) { if (indc[i] != i) { return true; } } } return false; } private boolean canMoveDown() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); int k= fElements.size() - 1; for (int i= indc.length - 1; i >= 0 ; i--, k--) { if (indc[i] != k) { return true; } } } return false; } /** * Returns the selected elements. */ public List getSelectedElements() { List result= new ArrayList(); if (fTable != null) { ISelection selection= fTable.getSelection(); if (selection instanceof IStructuredSelection) { Iterator iter= ((IStructuredSelection)selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } } } return result; } // ------- ListViewerAdapter private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener { // ------- ITableContentProvider Interface ------------ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // will never happen } public boolean isDeleted(Object element) { return false; } public void dispose() { } public Object[] getElements(Object obj) { return fElements.toArray(); } // ------- ISelectionChangedListener Interface ------------ public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } } private void doListSelected(SelectionChangedEvent event) { updateButtonState(); if (fListAdapter != null) { fListAdapter.selectionChanged(this); } } }
4,369
Bug 4369 F2 should work even if "Hide Text Hover" is enabled
- enable "Hide Text Hover" - position the cursor on a type - press F2 observe: nothing happens although I explicitly requested JavaDoc help.
resolved fixed
ce37c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:37:50Z"
"2001-10-11T11:33:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.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.RGB; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; 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.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.TextPresentation; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; 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.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.MarkerUtilities; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.tasklist.TaskList; 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.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.compare.JavaAddElementFromHistory; import org.eclipse.jdt.internal.ui.compare.JavaReplaceWithEditionAction; import org.eclipse.jdt.internal.ui.reorg.DeleteAction; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; /** * Java specific text editor. */ public class CompilationUnitEditor extends JavaEditor { /** * Responsible for highlighting matching pairs of brackets. */ class BracketHighlighter implements KeyListener, MouseListener, ISelectionChangedListener, ITextListener, ITextInputListener { /** * Highlights the brackets. */ class HighlightBrackets implements PaintListener { private JavaPairMatcher fMatcher= new JavaPairMatcher(new char[] { '{', '}', '(', ')', '[', ']' }); private Position fBracketPosition= new Position(0, 0); private int fAnchor; private boolean fIsActive= false; private StyledText fTextWidget; private Color fColor; public HighlightBrackets() { fTextWidget= fSourceViewer.getTextWidget(); } public void setHighlightColor(Color color) { fColor= color; } public void dispose() { if (fMatcher != null) { fMatcher.dispose(); fMatcher= null; } fColor= null; fTextWidget= null; } public void deactivate(boolean redraw) { if (fIsActive) { fIsActive= false; fTextWidget.removePaintListener(this); fManager.unmanage(fBracketPosition); if (redraw) handleDrawRequest(null); } } public void run() { Point selection= fSourceViewer.getSelectedRange(); if (selection.y > 0) { deactivate(true); return; } IRegion pair= fMatcher.match(fSourceViewer.getDocument(), selection.x); if (pair == null) { deactivate(true); return; } if (fIsActive) { // only if different if (pair.getOffset() != fBracketPosition.getOffset() || pair.getLength() != fBracketPosition.getLength() || fMatcher.getAnchor() != fAnchor) { // remove old highlighting handleDrawRequest(null); // update position fBracketPosition.isDeleted= false; fBracketPosition.offset= pair.getOffset(); fBracketPosition.length= pair.getLength(); fAnchor= fMatcher.getAnchor(); // apply new highlighting handleDrawRequest(null); } } else { fIsActive= true; fBracketPosition.isDeleted= false; fBracketPosition.offset= pair.getOffset(); fBracketPosition.length= pair.getLength(); fAnchor= fMatcher.getAnchor(); fTextWidget.addPaintListener(this); fManager.manage(fBracketPosition); handleDrawRequest(null); } } public void paintControl(PaintEvent event) { if (fTextWidget != null) handleDrawRequest(event.gc); } private void handleDrawRequest(GC gc) { IRegion region= fSourceViewer.getVisibleRegion(); int offset= fBracketPosition.getOffset(); int length= fBracketPosition.getLength(); if (region.getOffset() <= offset && region.getOffset() + region.getLength() >= offset + length) { offset -= region.getOffset(); if (fMatcher.RIGHT == fAnchor) draw(gc, offset, 1); else draw(gc, offset + length -1, 1); } } private void draw(GC gc, int offset, int length) { if (gc != null) { Point left= fTextWidget.getLocationAtOffset(offset); Point right= fTextWidget.getLocationAtOffset(offset + length); gc.setForeground(fColor); gc.drawRectangle(left.x, left.y, right.x - left.x - 1, gc.getFontMetrics().getHeight() - 1); } else { fTextWidget.redrawRange(offset, length, true); } } }; /** * Manages the registration and updating of the bracket position. */ class BracketPositionManager { private IDocument fDocument; private IPositionUpdater fPositionUpdater; private String fCategory; public BracketPositionManager() { fCategory= getClass().getName() + hashCode(); fPositionUpdater= new DefaultPositionUpdater(fCategory); } public void install(IDocument document) { fDocument= document; fDocument.addPositionCategory(fCategory); fDocument.addPositionUpdater(fPositionUpdater); } public void dispose() { uninstall(fDocument); } public void uninstall(IDocument document) { if (document == fDocument && document != null) { try { fDocument.removePositionUpdater(fPositionUpdater); fDocument.removePositionCategory(fCategory); } catch (BadPositionCategoryException x) { // should not happen } fDocument= null; } } public void manage(Position position) { try { fDocument.addPosition(fCategory, position); } catch (BadPositionCategoryException x) { // should not happen } catch (BadLocationException x) { // should not happen } } public void unmanage(Position position) { try { fDocument.removePosition(fCategory, position); } catch (BadPositionCategoryException x) { // should not happen } } }; private BracketPositionManager fManager= new BracketPositionManager(); private HighlightBrackets fHighlightBrackets; private ISourceViewer fSourceViewer; private boolean fTextChanged= false; public BracketHighlighter(ISourceViewer sourceViewer) { fSourceViewer= sourceViewer; fHighlightBrackets= new HighlightBrackets(); } public void setHighlightColor(Color color) { fHighlightBrackets.setHighlightColor(color); } public void install() { fManager.install(fSourceViewer.getDocument()); fSourceViewer.addTextInputListener(this); ISelectionProvider provider= fSourceViewer.getSelectionProvider(); provider.addSelectionChangedListener(this); fSourceViewer.addTextListener(this); StyledText text= fSourceViewer.getTextWidget(); text.addKeyListener(this); text.addMouseListener(this); } public void dispose() { if (fManager != null) { fManager.dispose(); fManager= null; } if (fHighlightBrackets != null) { fHighlightBrackets.dispose(); fHighlightBrackets= null; } if (fSourceViewer != null && fBracketHighlighter != null) { fSourceViewer.removeTextInputListener(this); ISelectionProvider provider= fSourceViewer.getSelectionProvider(); provider.removeSelectionChangedListener(this); fSourceViewer.removeTextListener(this); StyledText text= fSourceViewer.getTextWidget(); if (text != null && !text.isDisposed()) { text.removeKeyListener(fBracketHighlighter); text.removeMouseListener(fBracketHighlighter); } fSourceViewer= null; } } /* * @see KeyListener#keyPressed(KeyEvent) */ public void keyPressed(KeyEvent e) { fTextChanged= false; } /* * @see KeyListener#keyReleased(KeyEvent) */ public void keyReleased(KeyEvent e) { if (!fTextChanged) fHighlightBrackets.run(); } /* * @see MouseListener#mouseDoubleClick(MouseEvent) */ public void mouseDoubleClick(MouseEvent e) { } /* * @see MouseListener#mouseDown(MouseEvent) */ public void mouseDown(MouseEvent e) { } /* * @see MouseListener#mouseUp(MouseEvent) */ public void mouseUp(MouseEvent e) { fHighlightBrackets.run(); } /* * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { fHighlightBrackets.run(); } /* * @see ITextListener#textChanged(TextEvent) */ public void textChanged(TextEvent event) { fTextChanged= true; Control control= fSourceViewer.getTextWidget(); if (control != null) { control.getDisplay().asyncExec(new Runnable() { public void run() { if (fTextChanged && fHighlightBrackets != null) fHighlightBrackets.run(); } }); } } /* * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput != null) { fHighlightBrackets.deactivate(false); fManager.uninstall(oldInput); } } /* * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput != null) fManager.install(newInput); } }; class InternalSourceViewer extends SourceViewer { public InternalSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { super(parent, ruler, styles); } public IContentAssistant getContentAssistant() { return fContentAssistant; } }; /** Preference key for matching brackets */ public final static String MATCHING_BRACKETS= "matchingBrackets"; /** Preference key for matching brackets color */ public final static String MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; /** The status line clearer */ protected ISelectionChangedListener fStatusLineClearer; /** 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 bracket highlighter */ private BracketHighlighter fBracketHighlighter; /** * 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$ fSavePolicy= null; fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this); } /* * @see AbstractTextEditor#createActions */ protected void createActions() { super.createActions(); setAction("ContentAssistProposal", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this, ISourceViewer.CONTENTASSIST_PROPOSALS)); //$NON-NLS-1$ //$NON-NLS-2$ setAction("AddImportOnSelection", new AddImportOnSelectionAction(this)); //$NON-NLS-1$ setAction("OrganizeImports", new OrganizeImportsAction(this)); //$NON-NLS-1$ setAction("Comment", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX)); //$NON-NLS-1$ //$NON-NLS-2$ setAction("Uncomment", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX)); //$NON-NLS-1$ //$NON-NLS-2$ setAction("Format", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT)); //$NON-NLS-1$ //$NON-NLS-2$ setAction("AddBreakpoint", new AddBreakpointAction(this)); //$NON-NLS-1$ setAction("ManageBreakpoints", new BreakpointRulerAction(getVerticalRuler(), this)); //$NON-NLS-1$ setAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK, getAction("ManageBreakpoints")); //$NON-NLS-1$ } /* * @see JavaEditor#getElementAt */ protected IJavaElement getElementAt(int offset) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { try { unit.reconcile(); return unit.getElementAt(offset); } catch (JavaModelException x) { } } } return null; } /* * @see JavaEditor#getCorrespondingElement(IJavaElement) */ protected IJavaElement getCorrespondingElement(IJavaElement element) { try { return EditorUtility.getWorkingCopy(element, true); } catch (JavaModelException x) { // nothing found, be tolerant and go on } return null; } /* * @see AbstractEditor#editorContextMenuAboutToChange */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); addAction(menu, IContextMenuConstants.GROUP_GENERATE, "ContentAssistProposal"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_GENERATE, "AddImportOnSelection"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_GENERATE, "OrganizeImports"); //$NON-NLS-1$ addAction(menu, ITextEditorActionConstants.GROUP_ADD, "AddBreakpoint"); //$NON-NLS-1$ addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Comment"); //$NON-NLS-1$ addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Uncomment"); //$NON-NLS-1$ addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$ } /* * @see AbstractTextEditor#rulerContextMenuAboutToShow */ protected void rulerContextMenuAboutToShow(IMenuManager menu) { super.rulerContextMenuAboutToShow(menu); addAction(menu, "ManageBreakpoints"); //$NON-NLS-1$ } /* * @see JavaEditor#createOutlinePage */ protected JavaOutlinePage createOutlinePage() { JavaOutlinePage page= super.createOutlinePage(); page.setAction("OrganizeImports", new OrganizeImportsAction(this)); //$NON-NLS-1$ page.setAction("ReplaceWithEdition", new JavaReplaceWithEditionAction(page)); //$NON-NLS-1$ page.setAction("AddEdition", new JavaAddElementFromHistory(this, page)); //$NON-NLS-1$ DeleteAction deleteElement= new DeleteAction(page); page.setAction("DeleteElement", deleteElement); //$NON-NLS-1$ return page; } /* * @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#doSave(IProgressMonitor) */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) 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 { getStatusLineManager().setErrorMessage(""); //$NON-NLS-1$ IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { performSaveOperation(createSaveOperation(false), progressMonitor); } } else performSaveOperation(createSaveOperation(false), progressMonitor); } } /** * Jumps to the error next according to the given direction. */ public void gotoError(boolean forward) { ISelectionProvider provider= getSelectionProvider(); if (fStatusLineClearer != null) { provider.removeSelectionChangedListener(fStatusLineClearer); fStatusLineClearer= null; } ITextSelection s= (ITextSelection) provider.getSelection(); IMarker nextError= getNextError(s.getOffset(), forward); if (nextError != null) { gotoMarker(nextError); IWorkbenchPage page= getSite().getPage(); IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$ if (view instanceof TaskList) { StructuredSelection ss= new StructuredSelection(nextError); ((TaskList) view).setSelection(ss, true); } getStatusLineManager().setErrorMessage(nextError.getAttribute(IMarker.MESSAGE, "")); //$NON-NLS-1$ fStatusLineClearer= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { getSelectionProvider().removeSelectionChangedListener(fStatusLineClearer); fStatusLineClearer= null; getStatusLineManager().setErrorMessage(""); //$NON-NLS-1$ } }; provider.addSelectionChangedListener(fStatusLineClearer); } else { getStatusLineManager().setErrorMessage(""); //$NON-NLS-1$ } } private IMarker getNextError(int offset, boolean forward) { IMarker nextError= null; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= 0; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= model.getAnnotationIterator(); while (e.hasNext()) { Annotation a= (Annotation) e.next(); if (a instanceof MarkerAnnotation) { MarkerAnnotation ma= (MarkerAnnotation) a; IMarker marker= ma.getMarker(); if (MarkerUtilities.isMarkerType(marker, IMarker.PROBLEM)) { Position p= model.getPosition(a); if (!p.includes(offset)) { int currentDistance= 0; if (forward) { currentDistance= p.getOffset() - offset; if (currentDistance < 0) currentDistance= endOfDocument - offset + p.getOffset(); } else { currentDistance= offset - p.getOffset(); if (currentDistance < 0) currentDistance= offset + endOfDocument - p.getOffset(); } if (nextError == null || currentDistance < distance) { distance= currentDistance; nextError= marker; } } } } } return nextError; } /* * @see AbstractTextEditor#isSaveAsAllowed() */ public boolean isSaveAsAllowed() { return true; } /* * 1GF7WG9: ITPJUI:ALL - EXCEPTION: "Save As..." always fails */ protected IPackageFragment getPackage(IWorkspaceRoot root, IPath path) { if (path.segmentCount() == 1) { IProject project= root.getProject(path.toString()); if (project != null) { IJavaProject jProject= JavaCore.create(project); if (jProject != null) { try { IJavaElement element= jProject.findElement(new Path("")); //$NON-NLS-1$ if (element instanceof IPackageFragment) { IPackageFragment fragment= (IPackageFragment) element; IJavaElement parent= fragment.getParent(); if (parent instanceof IPackageFragmentRoot) { IPackageFragmentRoot pRoot= (IPackageFragmentRoot) parent; if ( !pRoot.isArchive() && !pRoot.isExternal() && path.equals(pRoot.getPath())) return fragment; } } } catch (JavaModelException x) { // ignore } } } return null; } else if (path.segmentCount() > 1) { IFolder folder= root.getFolder(path); IJavaElement element= JavaCore.create(folder); if (element instanceof IPackageFragment) return (IPackageFragment) element; } return null; } /* * 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. */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); SaveAsDialog dialog= new SaveAsDialog(shell); 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; } filePath= filePath.removeTrailingSeparator(); final String fileName= filePath.lastSegment(); IPath folderPath= filePath.removeLastSegments(1); if (folderPath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); /* * 1GF7WG9: ITPJUI:ALL - EXCEPTION: "Save As..." always fails */ final IPackageFragment fragment= getPackage(root, folderPath); IFile file= root.getFile(filePath); final FileEditorInput newInput= new FileEditorInput(file); WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(final IProgressMonitor monitor) throws CoreException { if (fragment != null) { try { // copy to another package IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); /* * 1GJXY0L: ITPJUI:WINNT - NPE during save As in Java editor * Introduced null check, just go on in the null case */ if (unit != null) { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Changed false to true. */ unit.copy(fragment, null, fileName, true, monitor); return; } } catch (JavaModelException x) { } } // if (fragment == null) then copy to a directory which is not a package // if (unit == null) copy the file that is not a compilation unit /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Changed false to true. */ getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); } }; boolean success= false; try { if (fragment == null) getDocumentProvider().aboutToChange(newInput); new ProgressMonitorDialog(shell).run(false, true, op); setInput(newInput); success= true; } catch (InterruptedException x) { } catch (InvocationTargetException x) { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Missing resources. */ 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 { if (fragment == null) getDocumentProvider().changed(newInput); if (progressMonitor != null) progressMonitor.setCanceled(!success); } } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); fJavaEditorErrorTickUpdater.setAnnotationModel(getDocumentProvider().getAnnotationModel(input)); } private void startBracketHighlighting() { if (fBracketHighlighter == null) { ISourceViewer sourceViewer= getSourceViewer(); fBracketHighlighter= new BracketHighlighter(sourceViewer); fBracketHighlighter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); fBracketHighlighter.install(); } } private void stopBracketHighlighting() { if (fBracketHighlighter != null) { fBracketHighlighter.dispose(); fBracketHighlighter= null; } } private boolean isBracketHighlightingEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(MATCHING_BRACKETS); } private Color getColor(String key) { RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), key); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } /* * @see AbstractTextEditor#dispose() */ public void dispose() { if (fJavaEditorErrorTickUpdater != null) { fJavaEditorErrorTickUpdater.setAnnotationModel(null); fJavaEditorErrorTickUpdater= null; } stopBracketHighlighting(); super.dispose(); } /* * @see AbstractTextEditor#createPartControl(Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); if (isBracketHighlightingEnabled()) startBracketHighlighting(); } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { String p= event.getProperty(); if (MATCHING_BRACKETS.equals(p)) { if (isBracketHighlightingEnabled()) startBracketHighlighting(); else stopBracketHighlighting(); return; } if (MATCHING_BRACKETS_COLOR.equals(p)) { if (fBracketHighlighter != null) fBracketHighlighter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); return; } InternalSourceViewer isv= (InternalSourceViewer) getSourceViewer(); IContentAssistant c= isv.getContentAssistant(); if (c instanceof ContentAssistant) ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event); } finally { super.handlePreferenceStoreChanged(event); } } /* * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { String p= event.getProperty(); boolean affects=MATCHING_BRACKETS_COLOR.equals(p); return affects ? affects : super.affectsTextPresentation(event); } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return new InternalSourceViewer(parent, ruler, styles); } }
4,369
Bug 4369 F2 should work even if "Hide Text Hover" is enabled
- enable "Hide Text Hover" - position the cursor on a type - press F2 observe: nothing happens although I explicitly requested JavaDoc help.
resolved fixed
ce37c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:37:50Z"
"2001-10-11T11:33:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/WorkInProgressPreferencePage.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.FieldEditorPreferencePage; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.DialogPageContextComputer; 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.JavaUIMessages; import org.eclipse.jdt.internal.ui.text.java.ExperimentalPreference; /* * The page for setting 'work in progress' features preferences. */ public class WorkInProgressPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public WorkInProgressPreferencePage() { super(GRID); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(JavaUIMessages.getString("WorkInProgressPreferencePage.description")); //$NON-NLS-1$ } public static void initDefaults(IPreferenceStore store) { store.setDefault(ExperimentalPreference.CODE_ASSIST_EXPERIMENTAL, false); } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), new DialogPageContextComputer(this, IJavaHelpContextIds.WORK_IN_PROGRESS_PREFERENCE_PAGE)); } protected void createFieldEditors() { Composite parent= getFieldEditorParent(); BooleanFieldEditor boolEditor= new BooleanFieldEditor( ExperimentalPreference.CODE_ASSIST_EXPERIMENTAL, JavaUIMessages.getString("WorkInProgressPreferencePage.codeassist.experimental"), //$NON-NLS-1$ parent ); addField(boolEditor); } /* * @see IWorkbenchPreferencePage#init(IWorkbench) */ public void init(IWorkbench workbench) { } }
4,369
Bug 4369 F2 should work even if "Hide Text Hover" is enabled
- enable "Hide Text Hover" - position the cursor on a type - press F2 observe: nothing happens although I explicitly requested JavaDoc help.
resolved fixed
ce37c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:37:50Z"
"2001-10-11T11:33:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaInformationProvider.java
4,369
Bug 4369 F2 should work even if "Hide Text Hover" is enabled
- enable "Hide Text Hover" - position the cursor on a type - press F2 observe: nothing happens although I explicitly requested JavaDoc help.
resolved fixed
ce37c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:37:50Z"
"2001-10-11T11:33:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaTextHover.java
package org.eclipse.jdt.internal.ui.text.java.hover; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.jdt.internal.ui.IPreferencesConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; /** * Caution: this implementation is a layer breaker and contains some "shortcuts" */ public class JavaTextHover implements ITextHover, IInformationProvider { class EditorWatcher implements IPartListener { /** * @see IPartListener#partOpened(IWorkbenchPart) */ public void partOpened(IWorkbenchPart part) { } /** * @see IPartListener#partDeactivated(IWorkbenchPart) */ public void partDeactivated(IWorkbenchPart part) { } /** * @see IPartListener#partClosed(IWorkbenchPart) */ public void partClosed(IWorkbenchPart part) { if (part == fEditor) { fEditor.getSite().getWorkbenchWindow().getPartService().removePartListener(fPartListener); fPartListener= null; IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } } /** * @see IPartListener#partActivated(IWorkbenchPart) */ public void partActivated(IWorkbenchPart part) { update(); } public void partBroughtToTop(IWorkbenchPart part) { update(); } }; class PropertyChangeListener implements IPropertyChangeListener { /** * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (IPreferencesConstants.EDITOR_SHOW_HOVER.equals(event.getProperty())) { Object newValue= event.getNewValue(); if (newValue instanceof Boolean) fEnabled= ((Boolean) newValue).booleanValue(); } } }; protected IEditorPart fEditor; protected IPartListener fPartListener; protected IPropertyChangeListener fPropertyChangeListener; protected String fCurrentPerspective; protected ITextHover[] fImplementations; protected boolean fEnabled; public JavaTextHover(IEditorPart editor) { fEditor= editor; if (fEditor != null) { fPartListener= new EditorWatcher(); IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow(); window.getPartService().addPartListener(fPartListener); fPropertyChangeListener= new PropertyChangeListener(); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.addPropertyChangeListener(fPropertyChangeListener); fEnabled= store.getBoolean(IPreferencesConstants.EDITOR_SHOW_HOVER); update(); } } protected void update() { IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow(); IWorkbenchPage page= window.getActivePage(); if (page != null) { String newPerspective= page.getPerspective().getId(); if (fCurrentPerspective == null || fCurrentPerspective != newPerspective) { fCurrentPerspective= newPerspective; if (IDebugUIConstants.ID_DEBUG_PERSPECTIVE.equals(fCurrentPerspective)) fImplementations= new ITextHover[] { new JavaDebugHover(fEditor) }; else fImplementations= new ITextHover[] { new JavaDebugHover(fEditor), new JavaTypeHover(fEditor) }; } } } /* * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { return getSubject(textViewer, offset); } /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { return getInformation(textViewer, hoverRegion); } /* * @see IInformationProvider#getSubject(ITextViewer, int) */ public IRegion getSubject(ITextViewer textViewer, int offset) { if (!fEnabled) return null; if (textViewer != null) return JavaWordFinder.findWord(textViewer.getDocument(), offset); return null; } /* * @see IInformationProvider#getInformation(ITextViewer, IRegion) */ public String getInformation(ITextViewer textViewer, IRegion subject) { if (fImplementations != null && fEnabled) { for (int i= 0; i < fImplementations.length; i++) { String s= fImplementations[i].getHoverInfo(textViewer, subject); if (s != null && s.trim().length() > 0) return s; } } return null; } }
4,369
Bug 4369 F2 should work even if "Hide Text Hover" is enabled
- enable "Hide Text Hover" - position the cursor on a type - press F2 observe: nothing happens although I explicitly requested JavaDoc help.
resolved fixed
ce37c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:37:50Z"
"2001-10-11T11:33:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaTypeHover.java
package org.eclipse.jdt.internal.ui.text.java.hover; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewer; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.text.HTMLPrinter; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; public class JavaTypeHover implements ITextHover { private IEditorPart fEditor; private final int LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED | JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS | JavaElementLabels.F_PRE_TYPE_SIGNATURE; public JavaTypeHover(IEditorPart editor) { fEditor= editor; } private ICodeAssist getCodeAssist() { if (fEditor != null) { IEditorInput input= fEditor.getEditorInput(); if (input instanceof IClassFileEditorInput) { IClassFileEditorInput cfeInput= (IClassFileEditorInput) input; return cfeInput.getClassFile(); } IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(input); } return null; } private String getInfoText(IMember member) { return JavaElementLabels.getElementLabel(member, LABEL_FLAGS); } /* * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { ICodeAssist resolve= getCodeAssist(); if (resolve != null) { try { IJavaElement[] result= resolve.codeSelect(hoverRegion.getOffset(), hoverRegion.getLength()); if (result == null) return null; int nResults= result.length; if (nResults == 0) return null; StringBuffer buffer= new StringBuffer(); if (nResults > 1) { for (int i= 0; i < result.length; i++) { HTMLPrinter.startBulletList(buffer); IJavaElement curr= result[i]; if (curr instanceof IMember) HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr)); HTMLPrinter.endBulletList(buffer); } } else { IJavaElement curr= result[0]; if (curr instanceof IMember) { IMember member= (IMember) curr; HTMLPrinter.addSmallHeader(buffer, getInfoText(member)); HTMLPrinter.addParagraph(buffer, JavaDocAccess.getJavaDoc(member)); } } if (buffer.length() > 0) { HTMLPrinter.insertPageProlog(buffer, 0); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); } } return null; } }
4,369
Bug 4369 F2 should work even if "Hide Text Hover" is enabled
- enable "Hide Text Hover" - position the cursor on a type - press F2 observe: nothing happens although I explicitly requested JavaDoc help.
resolved fixed
ce37c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:37:50Z"
"2001-10-11T11:33:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java
package org.eclipse.jdt.ui.text; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.DefaultTextDoubleClickStrategy; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.IAutoIndentStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.ITextDoubleClickStrategy; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.formatter.ContentFormatter; import org.eclipse.jface.text.formatter.IContentFormatter; import org.eclipse.jface.text.formatter.IFormattingStrategy; import org.eclipse.jface.text.information.IInformationPresenter; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.internal.html.HoverBrowserControl; import org.eclipse.jface.text.presentation.IPresentationReconciler; import org.eclipse.jface.text.presentation.PresentationReconciler; import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.reconciler.MonoReconciler; import org.eclipse.jface.text.rules.RuleBasedDamagerRepairer; import org.eclipse.jface.text.rules.RuleBasedScanner; import org.eclipse.jface.text.rules.Token; import org.eclipse.jface.text.source.IAnnotationHover; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor; import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector; import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy; import org.eclipse.jdt.internal.ui.text.java.hover.JavaTextHover; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor; /** * Configuration for a source viewer which shows Java code. * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> */ public class JavaSourceViewerConfiguration extends SourceViewerConfiguration { private JavaTextTools fJavaTextTools; private ITextEditor fTextEditor; /** * Creates a new Java source viewer configuration for viewers in the given editor * using the given Java tools. * * @param tools the Java tools to be used * @param editor the editor in which the configured viewer(s) will reside */ public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) { fJavaTextTools= tools; fTextEditor= editor; } /** * Returns the Java source code scanner for this configuration. * * @return the Java source code scanner */ protected RuleBasedScanner getCodeScanner() { return fJavaTextTools.getCodeScanner(); } /** * Returns the Java multiline comment scanner for this configuration. * * @return the Java multiline comment scanner */ protected RuleBasedScanner getMultilineCommentScanner() { return fJavaTextTools.getMultilineCommentScanner(); } /** * Returns the Java singleline comment scanner for this configuration. * * @return the Java singleline comment scanner */ protected RuleBasedScanner getSinglelineCommentScanner() { return fJavaTextTools.getSinglelineCommentScanner(); } /** * Returns the JavaDoc scanner for this configuration. * * @return the JavaDoc scanner */ protected RuleBasedScanner getJavaDocScanner() { return fJavaTextTools.getJavaDocScanner(); } /** * Returns the color manager for this configuration. * * @return the color manager */ protected IColorManager getColorManager() { return fJavaTextTools.getColorManager(); } /** * Returns the editor in which the configured viewer(s) will reside. * * @return the enclosing editor */ protected ITextEditor getEditor() { return fTextEditor; } /** * Returns the preference store used for by this configuration to initialize * the individula bits and pieces. */ protected IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /* * @see ISourceViewerConfiguration#getPresentationReconciler(ISourceViewer) */ public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { PresentationReconciler reconciler= new PresentationReconciler(); RuleBasedDamagerRepairer dr= new RuleBasedDamagerRepairer(getCodeScanner()); reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); dr= new RuleBasedDamagerRepairer(getJavaDocScanner()); reconciler.setDamager(dr, JavaPartitionScanner.JAVA_DOC); reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_DOC); dr= new RuleBasedDamagerRepairer(getMultilineCommentScanner()); reconciler.setDamager(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT); reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT); dr= new RuleBasedDamagerRepairer(getSinglelineCommentScanner()); reconciler.setDamager(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT); reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT); return reconciler; } /* * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { if (getEditor() != null) { ContentAssistant assistant= new ContentAssistant(); assistant.setContentAssistProcessor(new JavaCompletionProcessor(getEditor()), IDocument.DEFAULT_CONTENT_TYPE); assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), JavaPartitionScanner.JAVA_DOC); ContentAssistPreference.configure(assistant, getPreferenceStore()); assistant.setContextInformationPopupOrientation(assistant.CONTEXT_INFO_ABOVE); assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); return assistant; } return null; } /* * @see SourceViewerConfiguration#getReconciler(ISourceViewer) */ public IReconciler getReconciler(ISourceViewer sourceViewer) { if (getEditor() != null && getEditor().isEditable()) { MonoReconciler reconciler= new MonoReconciler(new JavaReconcilingStrategy(getEditor()), false); reconciler.setDelay(500); return reconciler; } return null; } /* * @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String) */ public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) { if (JavaPartitionScanner.JAVA_DOC.equals(contentType) || JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType)) return new JavaDocAutoIndentStrategy(); return new JavaAutoIndentStrategy(); } /* * @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String) */ public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { if (JavaPartitionScanner.JAVA_DOC.equals(contentType) || JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType) || JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT.equals(contentType)) return new DefaultTextDoubleClickStrategy(); return new JavaDoubleClickSelector(); } /* * @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String) */ public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) { return new String[] { "//", "" }; } /* * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String) */ public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) { return new String[] {"\t", " ", ""}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /* * @see SourceViewerConfiguration#getTabWidth(ISourceViewer) */ public int getTabWidth(ISourceViewer sourceViewer) { return 4; } /* * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) */ public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { return new JavaAnnotationHover(); } /* * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) */ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { return new JavaTextHover(getEditor()); } /* * @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer) */ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { return new String[] { IDocument.DEFAULT_CONTENT_TYPE, JavaPartitionScanner.JAVA_DOC, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT }; } /* * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer) */ public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { ContentFormatter formatter= new ContentFormatter(); IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer); formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE); formatter.enablePartitionAwareFormatting(false); formatter.setPartitionManagingPositionCategories(fJavaTextTools.getPartitionManagingPositionCategories()); return formatter; } /* * @see SourceViewerConfiguration#getHoverControlCreator(ISourceViewer) */ public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) { return getInformationControlCreator(sourceViewer, true); } private IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer, final boolean cutDown) { return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); return new DefaultInformationControl(parent, style, new HTMLTextPresenter(cutDown)); // return new HoverBrowserControl(parent); } }; } /* * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) */ public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) { InformationPresenter presenter= new InformationPresenter(getInformationControlCreator(sourceViewer, false)); IInformationProvider provider= new JavaTextHover(getEditor()); presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE); presenter.setInformationProvider(provider, JavaPartitionScanner.JAVA_DOC); presenter.setSizeConstraints(60, 10, true, true); return presenter; } }
4,369
Bug 4369 F2 should work even if "Hide Text Hover" is enabled
- enable "Hide Text Hover" - position the cursor on a type - press F2 observe: nothing happens although I explicitly requested JavaDoc help.
resolved fixed
ce37c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:37:50Z"
"2001-10-11T11:33:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/hover/IJavaEditorTextHover.java
6,308
Bug 6308 Open type dialog should trim entered value
Leading and trailing spaces should be ignored in the input field of this dialog
verified fixed
6e296de
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T17:49:38Z"
"2001-11-26T13:06:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/FilteredList.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jdt.internal.core.Assert; import org.eclipse.jdt.internal.ui.util.StringMatcher; /** * A composite widget which holds a list of elements for user selection. * The elements are sorted alphabetically. * Optionally, the elements can be filtered and duplicate entries can * be hidden (folding). */ public class FilteredList extends Composite { public interface FilterMatcher { /** * Sets the filter. * * @param pattern the filter pattern. * @param ignoreCase a flag indicating whether pattern matching is case insensitive or not. * @param ignoreWildCards a flag indicating whether wildcard characters are interpreted or not. */ void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards); /** * Returns <code>true</code> if the object matches the pattern, <code>false</code> otherwise. * <code>setFilter()</code> must have been called at least once prior to a call to this method. */ boolean match(Object element); } private class DefaultFilterMatcher implements FilterMatcher { private StringMatcher fMatcher; public void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards) { fMatcher= new StringMatcher(pattern + '*', ignoreCase, ignoreWildCards); } public boolean match(Object element) { return fMatcher.match(fRenderer.getText(element)); } } private Table fList; private ILabelProvider fRenderer; private boolean fMatchEmtpyString= true; private boolean fIgnoreCase; private boolean fAllowDuplicates; private String fFilter= ""; //$NON-NLS-1$ private TwoArrayQuickSorter fSorter; private Object[] fElements= new Object[0]; private Label[] fLabels; private Vector fImages= new Vector(); private int[] fFoldedIndices; private int fFoldedCount; private int[] fFilteredIndices; private int fFilteredCount; private FilterMatcher fFilterMatcher= new DefaultFilterMatcher(); private static class Label { public final String string; public final Image image; public Label(String string, Image image) { this.string= string; this.image= image; } public boolean equals(Label label) { if (label == null) return false; return string.equals(label.string) && image.equals(label.image); } } private class LabelComparator implements Comparator { private boolean fIgnoreCase; LabelComparator(boolean ignoreCase) { fIgnoreCase= ignoreCase; } public int compare(Object left, Object right) { Label leftLabel= (Label) left; Label rightLabel= (Label) right; int value= fIgnoreCase ? leftLabel.string.compareToIgnoreCase(rightLabel.string) : leftLabel.string.compareTo(rightLabel.string); if (value != 0) return value; // images are allowed to be null if (leftLabel.image == null) { return (rightLabel.image == null) ? 0 : -1; } else if (rightLabel.image == null) { return +1; } else { return fImages.indexOf(leftLabel.image) - fImages.indexOf(rightLabel.image); } } } /** * Constructs a new instance of a filtered list. * @param parent the parent composite. * @param style the widget style. * @param renderer the label renderer. * @param ignoreCase specifies whether sorting and folding is case sensitive. * @param allowDuplicates specifies whether folding of duplicates is desired. * @param matchEmptyString specifies whether empty filter strings should filter everything or nothing. */ public FilteredList(Composite parent, int style, ILabelProvider renderer, boolean ignoreCase, boolean allowDuplicates, boolean matchEmptyString) { super(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; setLayout(layout); fList= new Table(this, style); fList.setLayoutData(new GridData(GridData.FILL_BOTH)); fList.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { fRenderer.dispose(); } }); fRenderer= renderer; fIgnoreCase= ignoreCase; fSorter= new TwoArrayQuickSorter(new LabelComparator(ignoreCase)); fAllowDuplicates= allowDuplicates; fMatchEmtpyString= matchEmptyString; } /** * Sets the list of elements. * @param elements the elements to be shown in the list. */ public void setElements(Object[] elements) { if (elements == null) { fElements= new Object[0]; } else { // copy list for sorting fElements= new Object[elements.length]; System.arraycopy(elements, 0, fElements, 0, elements.length); } int length= fElements.length; // fill labels fLabels= new Label[length]; Set imageSet= new HashSet(); for (int i= 0; i != length; i++) { String text= fRenderer.getText(fElements[i]); Image image= fRenderer.getImage(fElements[i]); fLabels[i]= new Label(text, image); imageSet.add(image); } fImages.clear(); fImages.addAll(imageSet); fSorter.sort(fLabels, fElements); fFilteredIndices= new int[length]; fFilteredCount= filter(); fFoldedIndices= new int[length]; fFoldedCount= fold(); updateList(); } /** * Tests if the list (before folding and filtering) is empty. * @return returns <code>true</code> if the list is empty, <code>false</code> otherwise. */ public boolean isEmpty() { return (fElements == null) || (fElements.length == 0); } /** * Sets the filter matcher. */ public void setFilterMatcher(FilterMatcher filterMatcher) { Assert.isNotNull(filterMatcher); fFilterMatcher= filterMatcher; } /** * Adds a selection listener to the list. * @param listener the selection listener to be added. */ public void addSelectionListener(SelectionListener listener) { fList.addSelectionListener(listener); } /** * Removes a selection listener from the list. * @param listener the selection listener to be removed. */ public void removeSelectionListener(SelectionListener listener) { fList.removeSelectionListener(listener); } /** * Sets the selection of the list. * @param selection an array of indices specifying the selection. */ public void setSelection(int[] selection) { fList.setSelection(selection); } /** * Returns the selection of the list. * @return returns an array of indices specifying the current selection. */ public int[] getSelectionIndices() { return fList.getSelectionIndices(); } /** * Returns the selection of the list. * This is a convenience function for <code>getSelectionIndices()</code>. * @return returns the index of the selection, -1 for no selection. */ public int getSelectionIndex() { return fList.getSelectionIndex(); } /** * Sets the selection of the list. * @param elements the array of elements to be selected. */ public void setSelection(Object[] elements) { if ((elements == null) || (fElements == null)) return; // fill indices int[] indices= new int[elements.length]; for (int i= 0; i != elements.length; i++) { int j; for (j= 0; j != fFoldedCount; j++) { int max= (j == fFoldedCount - 1) ? fFilteredCount : fFoldedIndices[j + 1]; int l; for (l= fFoldedIndices[j]; l != max; l++) { // found matching element? if (fElements[fFilteredIndices[l]].equals(elements[i])) { indices[i]= j; break; } } if (l != max) break; } // not found if (j == fFoldedCount) indices[i] = 0; } fList.setSelection(indices); } /** * Returns an array of the selected elements. The type of the elements * returned in the list are the same as the ones passed with * <code>setElements</code>. The array does not contain the rendered strings. * @return returns the array of selected elements. */ public Object[] getSelection() { if (fList.isDisposed() || (fList.getSelectionCount() == 0)) return new Object[0]; int[] indices= fList.getSelectionIndices(); Object[] elements= new Object[indices.length]; for (int i= 0; i != indices.length; i++) elements[i]= fElements[fFilteredIndices[fFoldedIndices[indices[i]]]]; return elements; } /** * Sets the filter pattern. Current only prefix filter patterns are supported. * @param filter the filter pattern. */ public void setFilter(String filter) { fFilter= (filter == null) ? "" : filter; //$NON-NLS-1$ fFilteredCount= filter(); fFoldedCount= fold(); updateList(); } /** * Returns the filter pattern. * @return returns the filter pattern. */ public String getFilter() { return fFilter; } /** * Returns all elements which are folded together to one entry in the list. * @param index the index selecting the entry in the list. * @return returns an array of elements folded together, <code>null</code> if index is out of range. */ public Object[] getFoldedElements(int index) { if ((index < 0) || (index >= fFoldedCount)) return null; int start= fFoldedIndices[index]; int count= (index == fFoldedCount - 1) ? fFilteredCount - start : fFoldedIndices[index + 1] - start; Object[] elements= new Object[count]; for (int i= 0; i != count; i++) elements[i]= fElements[fFilteredIndices[start + i]]; return elements; } /* * Folds duplicate entries. Two elements are considered as a pair of * duplicates if they coiincide in the rendered string and image. * @return returns the number of elements after folding. */ private int fold() { if (fAllowDuplicates) { for (int i= 0; i != fFilteredCount; i++) fFoldedIndices[i]= i; // identity mapping return fFilteredCount; } else { int k= 0; Label last= null; for (int i= 0; i != fFilteredCount; i++) { int j= fFilteredIndices[i]; Label current= fLabels[j]; if (! current.equals(last)) { fFoldedIndices[k]= i; k++; last= current; } } return k; } } /* * Filters the list with the filter pattern. * @return returns the number of elements after filtering. */ private int filter() { if (((fFilter == null) || (fFilter.length() == 0)) && !fMatchEmtpyString) return 0; fFilterMatcher.setFilter(fFilter, fIgnoreCase, false); int k= 0; for (int i= 0; i != fElements.length; i++) { if (fFilterMatcher.match(fElements[i])) fFilteredIndices[k++]= i; } return k; } /* * Updates the list widget. */ private void updateList() { if (fList.isDisposed()) return; fList.setRedraw(false); // resize table int itemCount= fList.getItemCount(); if (fFoldedCount < itemCount) fList.remove(0, itemCount - fFoldedCount - 1); else if (fFoldedCount > itemCount) for (int i= 0; i != fFoldedCount - itemCount; i++) new TableItem(fList, SWT.NONE); // fill table TableItem[] items= fList.getItems(); for (int i= 0; i != fFoldedCount; i++) { TableItem item= items[i]; Label label= fLabels[fFilteredIndices[fFoldedIndices[i]]]; item.setText(label.string); item.setImage(label.image); } // select first item if any if (fList.getItemCount() > 0) fList.setSelection(0); fList.setRedraw(true); fList.notifyListeners(SWT.Selection, new Event()); } }
6,181
Bug 6181 Edit template panel doesn't resize
The panel is small and can't be resized. It also has a maximize button that is not operational.
verified fixed
ac79605
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T19:09:41Z"
"2001-11-21T19:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; 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.Text; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ILabelProvider; /** * An abstract class to select elements out of a list of elements. */ public abstract class AbstractElementListSelectionDialog extends SelectionStatusDialog { private ILabelProvider fRenderer; private boolean fIgnoreCase= true; private boolean fIsMultipleSelection= false; private boolean fMatchEmptyString= true; private boolean fAllowDuplicates= true; private Label fMessage; protected FilteredList fFilteredList; private Text fFilterText; private ISelectionValidator fValidator; private String fFilter= null; private String fEmptyListMessage= ""; //$NON-NLS-1$ private String fEmptySelectionMessage= ""; //$NON-NLS-1$ private int fWidth= 60; private int fHeight= 18; private Object[] fSelection= new Object[0]; /** * Constructs a list selection dialog. * @param renderer The label renderer used * @param ignoreCase Decides if the match string ignores lower/upppr case * @param multipleSelection Allow multiple selection */ protected AbstractElementListSelectionDialog(Shell parent, ILabelProvider renderer) { super(parent); fRenderer= renderer; } /** * Handles default selection (double click). * By default, the OK button is pressed. */ protected void handleDefaultSelected() { if (validateCurrentSelection()) buttonPressed(IDialogConstants.OK_ID); } /** * Specifies if sorting, filtering and folding is case sensitive. */ public void setIgnoreCase(boolean ignoreCase) { fIgnoreCase= ignoreCase; } /** * Returns if sorting, filtering and folding is case sensitive. */ public boolean isCaseIgnored() { return fIgnoreCase; } /** * Specifies whether everything or nothing should be filtered on * empty filter string. */ public void setMatchEmptyString(boolean matchEmptyString) { fMatchEmptyString= matchEmptyString; } /** * Specifies if multiple selection is allowed. */ public void setMultipleSelection(boolean multipleSelection) { fIsMultipleSelection= multipleSelection; } /** * Specifies whether duplicate entries are displayed or not. */ public void setAllowDuplicates(boolean allowDuplicates) { fAllowDuplicates= allowDuplicates; } /** * Sets the list size in unit of characters. * @param width the width of the list. * @param height the height of the list. */ public void setSize(int width, int height) { fWidth= width; fHeight= height; } /** * Sets the message to be displayed if the list is empty. * @param message the message to be displayed. */ public void setEmptyListMessage(String message) { fEmptyListMessage= message; } /** * Sets the message to be displayed if the selection is empty. * @param message the message to be displayed. */ public void setEmptySelectionMessage(String message) { fEmptySelectionMessage= message; } /** * Sets an optional validator to check if the selection is valid. * The validator is invoked whenever the selection changes. * @param validator the validator to validate the selection. */ public void setValidator(ISelectionValidator validator) { fValidator= validator; } /** * Sets the elements of the list (widget). * To be called within open(). * @param elements the elements of the list. */ protected void setListElements(Object[] elements) { Assert.isNotNull(fFilteredList); fFilteredList.setElements(elements); } /** * Sets the filter pattern. * @param filter the filter pattern. */ public void setFilter(String filter) { if (fFilterText == null) fFilter= filter; else fFilterText.setText(filter); } /** * Returns the current filter pattern. * @return returns the current filter pattern or <code>null<code> if filter was not set. */ public String getFilter() { if (fFilteredList == null) return fFilter; else return fFilteredList.getFilter(); } /** * Returns the indices referring the current selection. * To be called within open(). * @return returns the indices of the current selection. */ protected int[] getSelectionIndices() { Assert.isNotNull(fFilteredList); return fFilteredList.getSelectionIndices(); } /** * Returns an index referring the first current selection. * To be called within open(). * @return returns the indices of the current selection. */ protected int getSelectionIndex() { Assert.isNotNull(fFilteredList); return fFilteredList.getSelectionIndex(); } /** * Sets the selection referenced by an array of elements. * To be called within open(). * @param selection the indices of the selection. */ protected void setSelection(Object[] selection) { Assert.isNotNull(fFilteredList); fFilteredList.setSelection(selection); } /** * Returns an array of the currently selected elements. * To be called within or after open(). * @return returns an array of the currently selected elements. */ protected Object[] getSelectedElements() { Assert.isNotNull(fFilteredList); return fFilteredList.getSelection(); } /** * Returns all elements which are folded together to one entry in the list. * @param index the index selecting the entry in the list. * @return returns an array of elements folded together. */ public Object[] getFoldedElements(int index) { Assert.isNotNull(fFilteredList); return fFilteredList.getFoldedElements(index); } /** * Creates the message text widget and sets layout data. * @param composite the parent composite of the message area. */ protected Label createMessageArea(Composite composite) { Label label= super.createMessageArea(composite); GridData data= new GridData(); data.grabExcessVerticalSpace= false; data.grabExcessHorizontalSpace= true; data.horizontalAlignment= GridData.FILL; data.verticalAlignment= GridData.BEGINNING; label.setLayoutData(data); fMessage= label; return label; } /** * Handles a selection changed event. * By default, the current selection is validated. */ protected void handleSelectionChanged() { validateCurrentSelection(); } /** * Validates the current selection and updates the status line * accordingly. */ protected boolean validateCurrentSelection() { Assert.isNotNull(fFilteredList); IStatus status; Object[] elements= getSelectedElements(); if (elements.length > 0) { if (fValidator != null) { status= fValidator.validate(elements); } else { status= new StatusInfo(); } } else { if (fFilteredList.isEmpty()) { status= new StatusInfo(IStatus.ERROR, fEmptyListMessage); } else { status= new StatusInfo(IStatus.ERROR, fEmptySelectionMessage); } } updateStatus(status); return status.isOK(); } /* * @see Dialog#cancelPressed */ protected void cancelPressed() { setResult(null); super.cancelPressed(); } /** * Creates a filtered list. * @param parent the parent composite. * @return returns the filtered list widget. */ protected FilteredList createFilteredList(Composite parent) { int flags= SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | (fIsMultipleSelection ? SWT.MULTI : SWT.SINGLE); FilteredList list= new FilteredList(parent, flags, fRenderer, fIgnoreCase, fAllowDuplicates, fMatchEmptyString); GridData data= new GridData(); data.widthHint= convertWidthInCharsToPixels(fWidth); data.heightHint= convertHeightInCharsToPixels(fHeight); data.grabExcessVerticalSpace= true; data.grabExcessHorizontalSpace= true; data.horizontalAlignment= GridData.FILL; data.verticalAlignment= GridData.FILL; list.setLayoutData(data); list.setFilter((fFilter == null ? "" : fFilter)); //$NON-NLS-1$ list.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { handleDefaultSelected(); } public void widgetSelected(SelectionEvent e) { handleWidgetSelected(); } }); fFilteredList= list; return list; } // 3515 private void handleWidgetSelected() { Object[] newSelection= fFilteredList.getSelection(); if (newSelection.length != fSelection.length) { fSelection= newSelection; handleSelectionChanged(); } else { for (int i= 0; i != newSelection.length; i++) { if (!newSelection[i].equals(fSelection[i])) { fSelection= newSelection; handleSelectionChanged(); break; } } } } protected Text createFilterText(Composite parent) { Text text= new Text(parent, SWT.BORDER); GridData data= new GridData(); data.grabExcessVerticalSpace= false; data.grabExcessHorizontalSpace= true; data.horizontalAlignment= GridData.FILL; data.verticalAlignment= GridData.BEGINNING; text.setLayoutData(data); text.setText((fFilter == null ? "" : fFilter)); //$NON-NLS-1$ Listener listener= new Listener() { public void handleEvent(Event e) { fFilteredList.setFilter(fFilterText.getText()); } }; text.addListener(SWT.Modify, listener); text.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN) fFilteredList.setFocus(); } public void keyReleased(KeyEvent e) {} }); fFilterText= text; return text; } /* * @see Window#open() */ public int open() { BusyIndicator.showWhile(null, new Runnable() { public void run() { access$superOpen(); } }); return getReturnCode(); } private void access$superOpen() { super.open(); } /* * @see Window#create(Shell) */ public void create() { super.create(); Assert.isNotNull(fFilteredList); if (fFilteredList.isEmpty()) { handleEmptyList(); } else { validateCurrentSelection(); fFilterText.selectAll(); fFilterText.setFocus(); } } /** * Handles empty list by disabling widgets. */ protected void handleEmptyList() { fMessage.setEnabled(false); fFilterText.setEnabled(false); fFilteredList.setEnabled(false); } }
6,181
Bug 6181 Edit template panel doesn't resize
The panel is small and can't be resized. It also has a maximize button that is not operational.
verified fixed
ac79605
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-26T19:09:41Z"
"2001-11-21T19:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/EditTemplateDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.debug.internal.ui.TextViewerAction; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.text.template.Template; import org.eclipse.jdt.internal.ui.text.template.TemplateContext; import org.eclipse.jdt.internal.ui.text.template.TemplateInterpolator; import org.eclipse.jdt.internal.ui.text.template.TemplateMessages; import org.eclipse.jdt.internal.ui.text.template.TemplateVariableProcessor; import org.eclipse.jdt.internal.ui.text.template.VariableEvaluator; import org.eclipse.jdt.internal.ui.util.SWTUtil; /** * Dialog to edit a template. */ public class EditTemplateDialog extends StatusDialog { private static class SimpleJavaSourceViewerConfiguration extends JavaSourceViewerConfiguration { SimpleJavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) { super(tools, editor); } /* * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { ContentAssistant assistant= new ContentAssistant(); assistant.setContentAssistProcessor(new TemplateVariableProcessor(), IDocument.DEFAULT_CONTENT_TYPE); assistant.enableAutoActivation(true); assistant.setAutoActivationDelay(500); assistant.setProposalPopupOrientation(assistant.PROPOSAL_OVERLAY); assistant.setContextInformationPopupOrientation(assistant.CONTEXT_INFO_ABOVE); assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); Color background= getColorManager().getColor(new RGB(254, 241, 233)); assistant.setContextInformationPopupBackground(background); assistant.setContextSelectorBackground(background); assistant.setProposalSelectorBackground(background); return assistant; } } private static class TemplateVerifier implements VariableEvaluator { private String fErrorMessage; private boolean fHasAdjacentVariables; private boolean fEndsWithVariable; public void reset() { fErrorMessage= null; fHasAdjacentVariables= false; fEndsWithVariable= false; } public void acceptError(String message) { if (fErrorMessage == null) fErrorMessage= message; } public void acceptText(String text) { if (text.length() > 0) fEndsWithVariable= false; } public void acceptVariable(String variable) { if (fEndsWithVariable) fHasAdjacentVariables= true; fEndsWithVariable= true; } public boolean hasErrors() { return fHasAdjacentVariables || (fErrorMessage != null); } public String getErrorMessage() { if (fHasAdjacentVariables) return TemplateMessages.getString("EditTemplateDialog.error.adjacent.variables"); //$NON-NLS-1$ return fErrorMessage; } } private Template fTemplate; private Text fNameText; private Text fDescriptionText; private Combo fContextCombo; private SourceViewer fPatternEditor; private Button fInsertVariableButton; private TemplateInterpolator fInterpolator= new TemplateInterpolator(); private TemplateVerifier fVerifier= new TemplateVerifier(); private boolean fSuppressError= true; // #4354 private Map fGlobalActions= new HashMap(10); private List fSelectionActions = new ArrayList(3); public EditTemplateDialog(Shell parent, Template template, boolean edit) { super(parent); if (edit) setTitle(TemplateMessages.getString("EditTemplateDialog.title.edit")); //$NON-NLS-1$ else setTitle(TemplateMessages.getString("EditTemplateDialog.title.new")); //$NON-NLS-1$ fTemplate= template; } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite ancestor) { Composite parent= new Composite(ancestor, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; parent.setLayout(layout); parent.setLayoutData(new GridData(GridData.FILL_BOTH)); createLabel(parent, TemplateMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$ Composite composite= new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layout= new GridLayout(); layout.numColumns= 3; layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); fNameText= createText(composite); fNameText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (fSuppressError && (fNameText.getText().trim().length() != 0)) fSuppressError= false; updateButtons(); } }); createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$ fContextCombo= new Combo(composite, SWT.READ_ONLY); fContextCombo.setItems(new String[] {TemplateContext.JAVA, TemplateContext.JAVADOC}); createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$ fDescriptionText= createText(parent); composite= new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); Label patternLabel= createLabel(composite, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ fPatternEditor= createEditor(parent); Label filler= new Label(composite, SWT.NONE); filler.setLayoutData(new GridData(GridData.FILL_VERTICAL)); fInsertVariableButton= new Button(composite, SWT.NONE); fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton)); fInsertVariableButton.setText(TemplateMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ fInsertVariableButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); } public void widgetDefaultSelected(SelectionEvent e) {} }); fNameText.setText(fTemplate.getName()); fDescriptionText.setText(fTemplate.getDescription()); fContextCombo.select(getIndex(fTemplate.getContext())); initializeActions(); return composite; } private static GridData getButtonGridData(Button button) { GridData data= new GridData(GridData.FILL_HORIZONTAL); data.heightHint= SWTUtil.getButtonHeigthHint(button); return data; } private static Label createLabel(Composite parent, String name) { Label label= new Label(parent, SWT.NULL); label.setText(name); label.setLayoutData(new GridData()); return label; } private static Text createText(Composite parent) { Text text= new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return text; } private SourceViewer createEditor(Composite parent) { SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); viewer.configure(new SimpleJavaSourceViewerConfiguration(tools, null)); viewer.setEditable(true); viewer.setDocument(new Document(fTemplate.getPattern())); Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT); viewer.getTextWidget().setFont(font); Control control= viewer.getControl(); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(60); data.heightHint= convertHeightInCharsToPixels(5); control.setLayoutData(data); viewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { fInterpolator.interpolate(event.getDocumentEvent().getDocument().get(), fVerifier); updateUndoAction(); updateButtons(); } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateSelectionDependentActions(); } }); viewer.getTextWidget().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } public void keyReleased(KeyEvent e) {} }); return viewer; } private void handleKeyPressed(KeyEvent event) { if (event.stateMask != SWT.CTRL) return; switch (event.character) { case ' ': fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); break; // XXX CTRL-Z case (int) 'z' - (int) 'a' + 1: fPatternEditor.doOperation(ITextOperationTarget.UNDO); break; } } private void initializeActions() { TextViewerAction action= new TextViewerAction(fPatternEditor, fPatternEditor.UNDO); action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.UNDO, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.CUT); action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.CUT, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.COPY); action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.COPY, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.PASTE); action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.PASTE, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.SELECT_ALL); action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); action= new TextViewerAction(fPatternEditor, fPatternEditor.CONTENTASSIST_PROPOSALS); action.setText(TemplateMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$ fSelectionActions.add(ITextEditorActionConstants.CUT); fSelectionActions.add(ITextEditorActionConstants.COPY); fSelectionActions.add(ITextEditorActionConstants.PASTE); // create context menu MenuManager manager= new MenuManager(null, null); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { fillContextMenu(mgr); } }); StyledText text= fPatternEditor.getTextWidget(); Menu menu= manager.createContextMenu(text); text.setMenu(menu); } private void fillContextMenu(IMenuManager menu) { menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ } protected void updateSelectionDependentActions() { Iterator iterator= fSelectionActions.iterator(); while (iterator.hasNext()) updateAction((String)iterator.next()); } protected void updateUndoAction() { IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO); if (action instanceof IUpdate) ((IUpdate) action).update(); } protected void updateAction(String actionId) { IAction action= (IAction) fGlobalActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } private static int getIndex(String context) { if (context.equals(TemplateContext.JAVA)) return 0; else if (context.equals(TemplateContext.JAVADOC)) return 1; else return -1; } protected void okPressed() { fTemplate.setName(fNameText.getText()); fTemplate.setDescription(fDescriptionText.getText()); fTemplate.setContext(fContextCombo.getText()); fTemplate.setPattern(fPatternEditor.getTextWidget().getText()); super.okPressed(); } private void updateButtons() { boolean valid= fNameText.getText().trim().length() != 0; StatusInfo status= new StatusInfo(); if (!valid) { if (fSuppressError) status.setError(""); //$NON-NLS-1$ else status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ } else if (fVerifier.hasErrors()) { status.setError(fVerifier.getErrorMessage()); } updateStatus(status); } }
6,092
Bug 6092 JavaEditor should honor the tab width setting of the JavaFormatter
null
verified fixed
896299e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T15:00:03Z"
"2001-11-20T09:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Iterator; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddMethodEntryBreakpointAction; import org.eclipse.jdt.internal.ui.actions.AddWatchpointAction; import org.eclipse.jdt.internal.ui.actions.OpenImportDeclarationAction; import org.eclipse.jdt.internal.ui.actions.OpenSuperImplementationAction; import org.eclipse.jdt.internal.ui.actions.ShowInPackageViewAction; import org.eclipse.jdt.internal.ui.actions.StructuredSelectionProvider; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.util.PropertyChangeEvent; 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.swt.graphics.Image; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPartService; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; /** * Java specific text editor. */ public abstract class JavaEditor extends AbstractTextEditor implements ISelectionChangedListener { /** The outline page */ protected JavaOutlinePage fOutlinePage; /** Outliner context menu Id */ protected String fOutlinerContextMenuId; /** * Returns the most narrow java element including the given offset */ abstract protected IJavaElement getElementAt(int offset); /** * Returns the java element of this editor's input corresponding to the given IJavaElement */ abstract protected IJavaElement getCorrespondingElement(IJavaElement element); /** * Sets the input of the editor's outline page. */ abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input); /** * Default constructor. */ public JavaEditor() { super(); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this)); setRangeIndicator(new DefaultRangeIndicator()); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); } /** * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) * * This is the code that can be found in 1.0 fixing the bidi rendering of Java code. * Looking for something less vulernable in this stream. * protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { ISourceViewer viewer= super.createSourceViewer(parent, ruler, styles); StyledText text= viewer.getTextWidget(); text.setBidiColoring(true); return viewer; } */ /** * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.affectsBehavior(event); } /** * Sets the outliner's context menu ID. */ protected void setOutlinerContextMenuId(String menuId) { fOutlinerContextMenuId= menuId; } /** * @see AbstractTextEditor#editorContextMenuAboutToShow */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); addGroup(menu, ITextEditorActionConstants.GROUP_EDIT, IContextMenuConstants.GROUP_REORGANIZE); addGroup(menu, ITextEditorActionConstants.GROUP_EDIT, IContextMenuConstants.GROUP_GENERATE); addGroup(menu, ITextEditorActionConstants.GROUP_EDIT, IContextMenuConstants.GROUP_NEW); new JavaSearchGroup(false).fill(menu, ITextEditorActionConstants.GROUP_FIND, isTextSelectionEmpty()); addAction(menu, ITextEditorActionConstants.GROUP_FIND, "ShowJavaDoc"); addAction(menu, ITextEditorActionConstants.GROUP_FIND, "OpenSuperImplementation"); menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, new ShowInPackageViewAction()); addAction(menu, "RunToLine"); //$NON-NLS-1$ } /** * Creates the outline page used with this editor. */ protected JavaOutlinePage createOutlinePage() { JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this); page.addSelectionChangedListener(this); setOutlinePageInput(page, getEditorInput()); // page.setAction("ShowTypeHierarchy", new ShowTypeHierarchyAction(page)); //$NON-NLS-1$ page.setAction("OpenImportDeclaration", new OpenImportDeclarationAction(page)); //$NON-NLS-1$ page.setAction("ShowInPackageView", new ShowInPackageViewAction()); //$NON-NLS-1$ page.setAction("AddMethodEntryBreakpoint", new AddMethodEntryBreakpointAction(page)); //$NON-NLS-1$ page.setAction("AddWatchpoint", new AddWatchpointAction(page)); // $NON-NLS-1$ StructuredSelectionProvider selectionProvider= StructuredSelectionProvider.createFrom(page); page.setAction("OpenSuperImplementation", new OpenSuperImplementationAction(selectionProvider)); // $NON-NLS-1$ return page; } /** * Informs the editor that its outliner has been closed. */ public void outlinePageClosed() { if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(this); fOutlinePage= null; resetHighlightRange(); } } /* * Get the dektop's StatusLineManager */ protected IStatusLineManager getStatusLineManager() { IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) { return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); } return null; } /** * @see AbstractTextEditor#getAdapter(Class) */ public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { if (fOutlinePage == null) fOutlinePage= createOutlinePage(); return fOutlinePage; } return super.getAdapter(required); } protected void setSelection(ISourceReference reference, boolean moveCursor) { if (reference != null) { try { ISourceRange range= reference.getSourceRange(); if (range == null) return; int offset= range.getOffset(); int length= range.getLength(); if (offset > -1 && length >= 0) { setHighlightRange(offset, length, moveCursor); if (moveCursor && (reference instanceof IMember)) { range= ((IMember) reference).getNameRange(); offset= range.getOffset(); length= range.getLength(); if (range != null && offset > -1 && length > 0) { if (getSourceViewer() != null) { getSourceViewer().revealRange(offset, length); getSourceViewer().setSelectedRange(offset, length); } } } } return; } catch (JavaModelException x) { } catch (IllegalArgumentException x) { } } if (moveCursor) resetHighlightRange(); } public void setSelection(IJavaElement element) { if (element == null || element instanceof ICompilationUnit) { /* * If the element is an ICompilationUnit this unit is either the input * of this editor or not being displayed. In both cases, nothing should * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) */ return; } IJavaElement corresponding= getCorrespondingElement(element); if (corresponding instanceof ISourceReference) { ISourceReference reference= (ISourceReference) corresponding; // set hightlight range setSelection(reference, true); // set outliner selection if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(this); fOutlinePage.select(reference); fOutlinePage.addSelectionChangedListener(this); } } } public void selectionChanged(SelectionChangedEvent event) { ISourceReference reference= null; ISelection selection= event.getSelection(); Iterator iter= ((IStructuredSelection) selection).iterator(); while (iter.hasNext()) { Object o= iter.next(); if (o instanceof ISourceReference) { reference= (ISourceReference) o; break; } } if (!isActivePart() && JavaPlugin.getActivePage() != null) JavaPlugin.getActivePage().bringToTop(this); setSelection(reference, !isActivePart()); } /** * @see AbstractTextEditor#adjustHighlightRange(int, int) */ protected void adjustHighlightRange(int offset, int length) { try { IJavaElement element= getElementAt(offset); while (element instanceof ISourceReference) { ISourceRange range= ((ISourceReference) element).getSourceRange(); if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) { setHighlightRange(range.getOffset(), range.getLength(), true); if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(this); fOutlinePage.select((ISourceReference) element); fOutlinePage.addSelectionChangedListener(this); } return; } element= element.getParent(); } } catch (JavaModelException x) { } resetHighlightRange(); } protected boolean isActivePart() { IWorkbenchWindow window= getSite().getWorkbenchWindow(); IPartService service= window.getPartService(); return (this == service.getActivePart()); } /** * @see AbstractTextEditor#doSetInput */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); setOutlinePageInput(fOutlinePage, input); } protected void createActions() { super.createActions(); setAction("ShowJavaDoc", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION)); setAction("RunToLine", new RunToLineAction(this)); //$NON-NLS-1$ StructuredSelectionProvider provider= StructuredSelectionProvider.createFrom(getSite().getWorkbenchWindow().getSelectionService()); setAction("OpenSuperImplementation", new OpenSuperImplementationAction(provider)); //$NON-NLS-1$ } private boolean isTextSelectionEmpty() { ISelection selection= getSelectionProvider().getSelection(); if (!(selection instanceof ITextSelection)) return true; return ((ITextSelection)selection).getLength() == 0; } public void updatedTitleImage(Image image) { setTitleImage(image); } }
6,092
Bug 6092 JavaEditor should honor the tab width setting of the JavaFormatter
null
verified fixed
896299e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T15:00:03Z"
"2001-11-20T09:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeFormatterPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ 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.Hashtable; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.core.runtime.IStatus; 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.source.SourceViewer; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.formatter.CodeFormatter; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.JavaUIMessages; 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 code formatter options */ public class CodeFormatterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { // Preference store keys, see JavaCore.getOptions private static final String PREF_NEWLINE_OPENING_BRACES= "org.eclipse.jdt.core.formatter.newline.openingBrace"; private static final String PREF_NEWLINE_CONTROL_STATEMENT= "org.eclipse.jdt.core.formatter.newline.controlStatement"; private static final String PREF_NEWLINE_CLEAR_ALL= "org.eclipse.jdt.core.formatter.newline.clearAll"; private static final String PREF_NEWLINE_ELSE_IF= "org.eclipse.jdt.core.formatter.newline.elseIf"; private static final String PREF_NEWLINE_EMPTY_BLOCK= "org.eclipse.jdt.core.formatter.newline.emptyBlock"; private static final String PREF_LINE_SPLIT= "org.eclipse.jdt.core.formatter.lineSplit"; private static final String PREF_STYLE_COMPACT_ASSIGNEMENT= "org.eclipse.jdt.core.formatter.style.assignment"; private static final String PREF_TAB_CHAR= "org.eclipse.jdt.core.formatter.tabulation.char"; private static final String PREF_TAB_SIZE= "org.eclipse.jdt.core.formatter.tabulation.size"; // values private static final String INSERT= "insert"; private static final String DO_NOT_INSERT= "do not insert"; private static final String COMPACT= "compact"; private static final String NORMAL= "normal"; private static final String TAB= "tab"; private static final String SPACE= "space"; private static final String CLEAR_ALL= "clear all"; private static final String PRESERVE_ONE= "preserve one"; private static String[] getAllKeys() { return new String[] { PREF_NEWLINE_OPENING_BRACES, PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL, PREF_NEWLINE_ELSE_IF, PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT, PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_TAB_CHAR, PREF_TAB_SIZE }; } /** * Gets the currently configured tab size */ public static int getTabSize() { String string= (String) JavaCore.getOptions().get(PREF_TAB_SIZE); return getIntValue(string, 4); } /** * Gets the current compating assignement configuration */ public static boolean isCompactingAssignment() { return COMPACT.equals(JavaCore.getOptions().get(PREF_STYLE_COMPACT_ASSIGNEMENT)); } /** * Gets the current compating assignement configuration */ public static boolean useSpaces() { return SPACE.equals(JavaCore.getOptions().get(PREF_TAB_CHAR)); } private static int getIntValue(String string, int dflt) { try { return Integer.parseInt(string); } catch (NumberFormatException e) { } return dflt; } /** * Initializes the current options (read from preference store) */ public static void initDefaults(IPreferenceStore store) { Hashtable hashtable= JavaCore.getDefaultOptions(); Hashtable currOptions= JavaCore.getOptions(); String[] allKeys= getAllKeys(); for (int i= 0; i < allKeys.length; i++) { String key= allKeys[i]; String defValue= (String) hashtable.get(key); if (defValue != null) { store.setDefault(key, defValue); } else { JavaPlugin.logErrorMessage("CodeFormatterPreferencePage: value is null: " + key); } // update the JavaCore options from the pref store String val= store.getString(key); if (val != null) { currOptions.put(key, val); } } JavaCore.setOptions(currOptions); } private static class ControlData { private String fKey; private String[] fValues; public ControlData(String key, String[] values) { fKey= key; fValues= values; } public String getKey() { return fKey; } public String getValue(boolean selection) { int index= selection ? 0 : 1; return fValues[index]; } public String getValue(int index) { return fValues[index]; } public int getSelection(String value) { for (int i= 0; i < fValues.length; i++) { if (value.equals(fValues[i])) { return i; } } throw new IllegalArgumentException(); } } private Hashtable fWorkingValues; private ArrayList fCheckBoxes; private ArrayList fTextBoxes; private SelectionListener fButtonSelectionListener; private ModifyListener fTextModifyListener; private String fPreviewText; private IDocument fPreviewDocument; private Text fTabSizeTextBox; public CodeFormatterPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(JavaUIMessages.getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$ fWorkingValues= JavaCore.getOptions(); fCheckBoxes= new ArrayList(); fTextBoxes= new ArrayList(); fButtonSelectionListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) {} public void widgetSelected(SelectionEvent e) { if (!e.widget.isDisposed()) { controlChanged((Button) e.widget); } } }; fTextModifyListener= new ModifyListener() { public void modifyText(ModifyEvent e) { if (!e.widget.isDisposed()) { textChanged((Text) e.widget); } } }; fPreviewDocument= new Document(); fPreviewText= loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$ } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), new DialogPageContextComputer(this, IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE)); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; Composite composite= new Composite(parent, SWT.NONE); composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); String[] insertNotInsert= new String[] { INSERT, DO_NOT_INSERT }; layout= new GridLayout(); layout.numColumns= 2; Composite newlineComposite= new Composite(folder, SWT.NULL); newlineComposite.setLayout(layout); String label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, insertNotInsert); label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, insertNotInsert); label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, new String[] { CLEAR_ALL, PRESERVE_ONE } ); label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, insertNotInsert); label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, insertNotInsert); layout= new GridLayout(); layout.numColumns= 2; Composite lineSplittingComposite= new Composite(folder, SWT.NULL); lineSplittingComposite.setLayout(layout); label= JavaUIMessages.getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$ addTextField(lineSplittingComposite, label, PREF_LINE_SPLIT); layout= new GridLayout(); layout.numColumns= 2; Composite styleComposite= new Composite(folder, SWT.NULL); styleComposite.setLayout(layout); label= JavaUIMessages.getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$ addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, new String[] { COMPACT, NORMAL } ); label= JavaUIMessages.getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$ addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, SPACE } ); label= JavaUIMessages.getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$ fTabSizeTextBox= addTextField(styleComposite, label, PREF_TAB_SIZE); fTabSizeTextBox.setEnabled(!usesTabs()); TabItem item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$ item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL)); item.setControl(newlineComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$ item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE)); item.setControl(lineSplittingComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$ item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_REF)); item.setControl(styleComposite); createPreview(parent); updatePreview(); return composite; } private Control createPreview(Composite parent) { SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); previewViewer.configure(new JavaSourceViewerConfiguration(tools, null)); previewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); previewViewer.setEditable(false); previewViewer.setDocument(fPreviewDocument); Control control= previewViewer.getControl(); GridData gdata= new GridData(GridData.FILL_BOTH); gdata.widthHint= convertWidthInCharsToPixels(80); gdata.heightHint= convertHeightInCharsToPixels(15); control.setLayoutData(gdata); return control; } private Button addCheckBox(Composite parent, String label, String key, String[] values) { ControlData data= new ControlData(key, values); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan= 2; Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); checkBox.setData(data); checkBox.setLayoutData(gd); String currValue= (String)fWorkingValues.get(key); checkBox.setSelection(data.getSelection(currValue) == 0); checkBox.addSelectionListener(fButtonSelectionListener); fCheckBoxes.add(checkBox); return checkBox; } private Text addTextField(Composite parent, String label, String key) { Label labelControl= new Label(parent, SWT.NONE); labelControl.setText(label); labelControl.setLayoutData(new GridData()); Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE); textBox.setData(key); textBox.setLayoutData(new GridData()); String currValue= (String)fWorkingValues.get(key); textBox.setText(String.valueOf(getIntValue(currValue, 1))); textBox.setTextLimit(3); textBox.addModifyListener(fTextModifyListener); GridData gd= new GridData(); gd.widthHint= convertWidthInCharsToPixels(5); textBox.setLayoutData(gd); fTextBoxes.add(textBox); return textBox; } private void controlChanged(Button button) { ControlData data= (ControlData) button.getData(); boolean selection= button.getSelection(); String newValue= data.getValue(selection); fWorkingValues.put(data.getKey(), newValue); updatePreview(); if (PREF_TAB_CHAR.equals(data.getKey())) { fTabSizeTextBox.setEnabled(!selection); updateStatus(new StatusInfo()); if (selection) { fTabSizeTextBox.setText((String)fWorkingValues.get(PREF_TAB_SIZE)); } } } private void textChanged(Text textControl) { String key= (String) textControl.getData(); String number= textControl.getText(); IStatus status= validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) { fWorkingValues.put(key, number); } updateStatus(status); updatePreview(); } /* * @see IPreferencePage#performOk() */ public boolean performOk() { String[] allKeys= getAllKeys(); // preserve other options // store in JCore and the preferences Hashtable actualOptions= JavaCore.getOptions(); IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < allKeys.length; i++) { String key= allKeys[i]; String val= (String) fWorkingValues.get(key); actualOptions.put(key, val); store.setValue(key, val); } JavaCore.setOptions(actualOptions); return super.performOk(); } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fWorkingValues= JavaCore.getDefaultOptions(); updateControls(); super.performDefaults(); } private String loadPreviewFile(String filename) { String separator= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer btxt= new StringBuffer(512); BufferedReader rin= null; try { rin= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); String line; while ((line= rin.readLine()) != null) { btxt.append(line); btxt.append(separator); } } catch (IOException io) { JavaPlugin.log(io); } finally { if (rin != null) { try { rin.close(); } catch (IOException e) {} } } return btxt.toString(); } private void updatePreview() { fPreviewDocument.set(CodeFormatter.format(fPreviewText, 0, fWorkingValues)); } private void updateControls() { // update the UI for (int i= fCheckBoxes.size() - 1; i >= 0; i--) { Button curr= (Button) fCheckBoxes.get(i); ControlData data= (ControlData) curr.getData(); String currValue= (String) fWorkingValues.get(data.getKey()); curr.setSelection(data.getSelection(currValue) == 0); } for (int i= fTextBoxes.size() - 1; i >= 0; i--) { Text curr= (Text) fTextBoxes.get(i); String key= (String) curr.getData(); String currValue= (String) fWorkingValues.get(key); curr.setText(currValue); } fTabSizeTextBox.setEnabled(!usesTabs()); } private IStatus validatePositiveNumber(String number) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(JavaUIMessages.getString("CodeFormatterPreferencePage.empty_input")); } else { try { int value= Integer.parseInt(number); if (value < 0) { status.setError(JavaUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); } } catch (NumberFormatException e) { status.setError(JavaUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); } } return status; } private void updateStatus(IStatus status) { if (!status.matches(IStatus.ERROR)) { // look if there are more severe errors for (int i= 0; i < fTextBoxes.size(); i++) { Text curr= (Text) fTextBoxes.get(i); if (!(curr == fTabSizeTextBox && usesTabs())) { IStatus currStatus= validatePositiveNumber(curr.getText()); status= StatusUtil.getMoreSevere(currStatus, status); } } } setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } private boolean usesTabs() { return TAB.equals(fWorkingValues.get(PREF_TAB_CHAR)); } }
6,092
Bug 6092 JavaEditor should honor the tab width setting of the JavaFormatter
null
verified fixed
896299e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T15:00:03Z"
"2001-11-20T09:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; 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.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.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.DialogPageContextComputer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.WorkbenchChainedTextFontFieldEditor; import org.eclipse.jdt.ui.text.IJavaColorConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; /* * The page for setting the editor options. */ public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { public final OverlayPreferenceStore.OverlayKey[] fKeys= new OverlayPreferenceStore.OverlayKey[] { new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_KEYWORD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_KEYWORD + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_TYPE), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_TYPE + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_STRING), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_STRING + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_DEFAULT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_DEFAULT + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_KEYWORD), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_KEYWORD + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_TAG), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_TAG + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_LINK), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_LINK + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_DEFAULT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_DEFAULT + "_bold"), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.MATCHING_BRACKETS_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.MATCHING_BRACKETS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.AUTOACTIVATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, ContentAssistPreference.AUTOACTIVATION_DELAY), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.AUTOINSERT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PROPOSALS_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PROPOSALS_FOREGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PARAMETERS_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PARAMETERS_FOREGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.SHOW_VISIBLE_PROPOSALS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.ORDER_PROPOSALS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.CASE_SENSITIVITY), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.ADD_IMPORT) }; private final String[][] fListModel= new String[][] { { "Multi-line comment", IJavaColorConstants.JAVA_MULTI_LINE_COMMENT }, { "Single-line comment", IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT }, { "Keywords", IJavaColorConstants.JAVA_KEYWORD }, { "Built-in types", IJavaColorConstants.JAVA_TYPE }, { "Strings", IJavaColorConstants.JAVA_STRING }, { "Others", IJavaColorConstants.JAVA_DEFAULT }, { "JavaDoc keywords", IJavaColorConstants.JAVADOC_KEYWORD }, { "JavaDoc HTML tags", IJavaColorConstants.JAVADOC_TAG }, { "JavaDoc links", IJavaColorConstants.JAVADOC_LINK }, {"JavaDoc others", IJavaColorConstants.JAVADOC_DEFAULT } }; private OverlayPreferenceStore fOverlayStore; private JavaTextTools fJavaTextTools; private Map fColorButtons= new HashMap(); private SelectionListener fColorButtonListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { ColorEditor editor= (ColorEditor) e.widget.getData(); PreferenceConverter.setValue(fOverlayStore, (String) fColorButtons.get(editor), editor.getColorValue()); } }; 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 WorkbenchChainedTextFontFieldEditor fFontEditor; private List fList; private ColorEditor fColorEditor; private Button fBoldCheckBox; private SourceViewer fPreviewViewer; public JavaEditorPreferencePage() { setDescription(JavaUIMessages.getString("JavaEditorPreferencePage.description")); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys); } public static void initDefaults(IPreferenceStore store) { Color color; Display display= Display.getDefault(); store.setDefault(CompilationUnitEditor.MATCHING_BRACKETS, true); color= display.getSystemColor(SWT.COLOR_BLUE); PreferenceConverter.setDefault(store, CompilationUnitEditor.MATCHING_BRACKETS_COLOR, color.getRGB()); WorkbenchChainedTextFontFieldEditor.startPropagate(store, JFaceResources.TEXT_FONT); color= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND); PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, color.getRGB()); color= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, color.getRGB()); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT, new RGB(63, 127, 95)); store.setDefault(IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + "_bold", false); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT, new RGB(63, 127, 95)); store.setDefault(IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + "_bold", false); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_KEYWORD, new RGB(127, 0, 85)); store.setDefault(IJavaColorConstants.JAVA_KEYWORD + "_bold", true); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_TYPE, new RGB(127, 0, 85)); store.setDefault(IJavaColorConstants.JAVA_TYPE + "_bold", true); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_STRING, new RGB(42, 0, 255)); store.setDefault(IJavaColorConstants.JAVA_STRING + "_bold", false); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_DEFAULT, new RGB(0, 0, 0)); store.setDefault(IJavaColorConstants.JAVA_DEFAULT + "_bold", false); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_KEYWORD, new RGB(127, 159, 191)); store.setDefault(IJavaColorConstants.JAVADOC_KEYWORD + "_bold", true); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_TAG, new RGB(127, 127, 159)); store.setDefault(IJavaColorConstants.JAVADOC_TAG + "_bold", false); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_LINK, new RGB(63, 63, 191)); store.setDefault(IJavaColorConstants.JAVADOC_LINK + "_bold", false); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_DEFAULT, new RGB(63, 95, 191)); store.setDefault(IJavaColorConstants.JAVADOC_DEFAULT + "_bold", false); store.setDefault(ContentAssistPreference.AUTOACTIVATION, true); store.setDefault(ContentAssistPreference.AUTOACTIVATION_DELAY, 500); store.setDefault(ContentAssistPreference.AUTOINSERT, false); PreferenceConverter.setDefault(store, ContentAssistPreference.PROPOSALS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, ContentAssistPreference.PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, ContentAssistPreference.PARAMETERS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, ContentAssistPreference.PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, ".,"); store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); store.setDefault(ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, false); store.setDefault(ContentAssistPreference.CASE_SENSITIVITY, false); store.setDefault(ContentAssistPreference.ORDER_PROPOSALS, false); store.setDefault(ContentAssistPreference.ADD_IMPORT, true); } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), new DialogPageContextComputer(this, IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE)); } private void handleListSelection() { int i= fList.getSelectionIndex(); String key= fListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fColorEditor.setColorValue(rgb); fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + "_bold")); } private Control createColorPage(Composite parent) { Composite colorComposite= new Composite(parent, SWT.NULL); colorComposite.setLayout(new GridLayout()); Label label= new Label(colorComposite, SWT.LEFT); label.setText("Colors"); label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite editorComposite= new Composite(colorComposite, SWT.NULL); 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); fList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NULL); 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("Foreground:"); gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fColorEditor= new ColorEditor(stylesComposite); Button colorButton= fColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; colorButton.setLayoutData(gd); label= new Label(stylesComposite, SWT.LEFT); label.setText("Bold:"); gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fBoldCheckBox= new Button(stylesComposite, SWT.CHECK); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; fBoldCheckBox.setLayoutData(gd); label= new Label(colorComposite, SWT.LEFT); label.setText("Preview"); label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control previewer= createPreviewer(colorComposite); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(80); gd.heightHint= convertHeightInCharsToPixels(15); previewer.setLayoutData(gd); fList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleListSelection(); } }); colorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fList.getSelectionIndex(); String key= fListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fColorEditor.getColorValue()); } }); fBoldCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fList.getSelectionIndex(); String key= fListModel[i][1]; fOverlayStore.setValue(key + "_bold", fBoldCheckBox.getSelection()); } }); return colorComposite; } private Control createPreviewer(Composite parent) { fJavaTextTools= new JavaTextTools(fOverlayStore); fPreviewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL); fPreviewViewer.configure(new JavaSourceViewerConfiguration(fJavaTextTools, null)); fPreviewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); fPreviewViewer.setEditable(false); String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); 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) { fPreviewViewer.invalidateTextPresentation(); } }); return fPreviewViewer.getControl(); } private Control createBehaviorPage(Composite parent) { Composite behaviorComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; behaviorComposite.setLayout(layout); String label= "Highlight matching brackets"; addCheckBox(behaviorComposite, label, CompilationUnitEditor.MATCHING_BRACKETS, 0); label= "Matching brackets highlight color:"; addColorButton(behaviorComposite, label, CompilationUnitEditor.MATCHING_BRACKETS_COLOR, 0); label= "Text font:"; addTextFontEditor(behaviorComposite, label, AbstractTextEditor.PREFERENCE_FONT); return behaviorComposite; } private Control createContentAssistPage(Composite parent) { Composite contentAssistComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; contentAssistComposite.setLayout(layout); String label= "Insert &single proposals automatically"; addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOINSERT, 0); label= "Show only proposals visible in the invocation &context"; addCheckBox(contentAssistComposite, label, ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, 0); // label= "Show only proposals with &matching cases"; // addCheckBox(contentAssistComposite, label, ContentAssistPreference.CASE_SENSITIVITY, 0); label= "Present proposals in &alphabetical order"; addCheckBox(contentAssistComposite, label, ContentAssistPreference.ORDER_PROPOSALS, 0); label= "&Enable auto activation"; addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION, 0); label= "Automatically add &import instead of qualified name"; addCheckBox(contentAssistComposite, label, ContentAssistPreference.ADD_IMPORT, 0); label= "Auto activation &delay:"; addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_DELAY, 4, 0); label= "Auto activation &triggers for Java:"; addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, 25, 0); label= "Auto activation tri&ggers for JavaDoc:"; addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, 25, 0); label= "&Background for completion proposals:"; addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_BACKGROUND, 0); label= "&Foreground for completion proposals:"; addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_FOREGROUND, 0); label= "B&ackground for method parameters:"; addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_BACKGROUND, 0); label= "F&oreground for method parameters:"; addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_FOREGROUND, 0); return contentAssistComposite; } /* * @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("&General"); item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE)); item.setControl(createBehaviorPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText("&Colors"); item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE)); item.setControl(createColorPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText("Code &Assist"); item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE)); item.setControl(createContentAssistPage(folder)); initialize(); return folder; } private void initialize() { fFontEditor.setPreferenceStore(getPreferenceStore()); fFontEditor.setPreferencePage(this); fFontEditor.load(); initializeFields(); for (int i= 0; i < fListModel.length; i++) fList.add(fListModel[i][0]); fList.getDisplay().asyncExec(new Runnable() { public void run() { fList.select(0); handleListSelection(); } }); } 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)); } } /* * @see PreferencePage#performOk() */ public boolean performOk() { fFontEditor.store(); fOverlayStore.propagate(); return true; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fFontEditor.loadDefault(); fOverlayStore.loadDefaults(); initializeFields(); handleListSelection(); super.performDefaults(); fPreviewViewer.invalidateTextPresentation(); } /* * @see DialogPage#dispose() */ public void dispose() { if (fJavaTextTools != null) { fJavaTextTools= null; } fFontEditor.setPreferencePage(null); fFontEditor.setPreferenceStore(null); if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } super.dispose(); } private void addColorButton(Composite parent, String label, String key, int indentation) { Label labelControl= new Label(parent, SWT.NONE); labelControl.setText(label); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= indentation; labelControl.setLayoutData(gd); ColorEditor editor= new ColorEditor(parent); Button button= editor.getButton(); button.setData(editor); gd= new GridData(); gd.horizontalAlignment= GridData.END; button.setLayoutData(gd); button.addSelectionListener(fColorButtonListener); fColorButtons.put(editor, key); } private void addCheckBox(Composite parent, String label, String key, int indentation) { Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= indentation; gd.horizontalSpan= 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); fCheckBoxes.put(checkBox, key); } private void addTextField(Composite parent, String label, String key, int textLimit, int indentation) { Label labelControl= new Label(parent, SWT.NONE); labelControl.setText(label); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= indentation; labelControl.setLayoutData(gd); Text textControl= new Text(parent, SWT.BORDER | SWT.SINGLE); gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= convertWidthInCharsToPixels(textLimit + 1); gd.horizontalAlignment= GridData.END; textControl.setLayoutData(gd); textControl.setTextLimit(textLimit); textControl.addModifyListener(fTextFieldListener); fTextFields.put(textControl, key); } private void addTextFontEditor(Composite parent, String label, String key) { Composite editorComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 3; editorComposite.setLayout(layout); fFontEditor= new WorkbenchChainedTextFontFieldEditor(key, label, editorComposite); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); } 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(); } }
6,092
Bug 6092 JavaEditor should honor the tab width setting of the JavaFormatter
null
verified fixed
896299e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T15:00:03Z"
"2001-11-20T09:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java
package org.eclipse.jdt.ui.text; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DefaultTextDoubleClickStrategy; import org.eclipse.jface.text.IAutoIndentStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.ITextDoubleClickStrategy; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.formatter.ContentFormatter; import org.eclipse.jface.text.formatter.IContentFormatter; import org.eclipse.jface.text.formatter.IFormattingStrategy; import org.eclipse.jface.text.information.IInformationPresenter; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.presentation.IPresentationReconciler; import org.eclipse.jface.text.presentation.PresentationReconciler; import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.reconciler.MonoReconciler; import org.eclipse.jface.text.rules.RuleBasedDamagerRepairer; import org.eclipse.jface.text.rules.RuleBasedScanner; import org.eclipse.jface.text.source.IAnnotationHover; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor; import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector; import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy; import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider; import org.eclipse.jdt.internal.ui.text.java.hover.JavaTextHover; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor; /** * Configuration for a source viewer which shows Java code. * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> */ public class JavaSourceViewerConfiguration extends SourceViewerConfiguration { private JavaTextTools fJavaTextTools; private ITextEditor fTextEditor; /** * Creates a new Java source viewer configuration for viewers in the given editor * using the given Java tools. * * @param tools the Java tools to be used * @param editor the editor in which the configured viewer(s) will reside */ public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) { fJavaTextTools= tools; fTextEditor= editor; } /** * Returns the Java source code scanner for this configuration. * * @return the Java source code scanner */ protected RuleBasedScanner getCodeScanner() { return fJavaTextTools.getCodeScanner(); } /** * Returns the Java multiline comment scanner for this configuration. * * @return the Java multiline comment scanner */ protected RuleBasedScanner getMultilineCommentScanner() { return fJavaTextTools.getMultilineCommentScanner(); } /** * Returns the Java singleline comment scanner for this configuration. * * @return the Java singleline comment scanner */ protected RuleBasedScanner getSinglelineCommentScanner() { return fJavaTextTools.getSinglelineCommentScanner(); } /** * Returns the JavaDoc scanner for this configuration. * * @return the JavaDoc scanner */ protected RuleBasedScanner getJavaDocScanner() { return fJavaTextTools.getJavaDocScanner(); } /** * Returns the color manager for this configuration. * * @return the color manager */ protected IColorManager getColorManager() { return fJavaTextTools.getColorManager(); } /** * Returns the editor in which the configured viewer(s) will reside. * * @return the enclosing editor */ protected ITextEditor getEditor() { return fTextEditor; } /** * Returns the preference store used for by this configuration to initialize * the individula bits and pieces. */ protected IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /* * @see ISourceViewerConfiguration#getPresentationReconciler(ISourceViewer) */ public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { PresentationReconciler reconciler= new PresentationReconciler(); RuleBasedDamagerRepairer dr= new RuleBasedDamagerRepairer(getCodeScanner()); reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); dr= new RuleBasedDamagerRepairer(getJavaDocScanner()); reconciler.setDamager(dr, JavaPartitionScanner.JAVA_DOC); reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_DOC); dr= new RuleBasedDamagerRepairer(getMultilineCommentScanner()); reconciler.setDamager(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT); reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT); dr= new RuleBasedDamagerRepairer(getSinglelineCommentScanner()); reconciler.setDamager(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT); reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT); return reconciler; } /* * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { if (getEditor() != null) { ContentAssistant assistant= new ContentAssistant(); assistant.setContentAssistProcessor(new JavaCompletionProcessor(getEditor()), IDocument.DEFAULT_CONTENT_TYPE); assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), JavaPartitionScanner.JAVA_DOC); ContentAssistPreference.configure(assistant, getPreferenceStore()); assistant.setContextInformationPopupOrientation(assistant.CONTEXT_INFO_ABOVE); assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); return assistant; } return null; } /* * @see SourceViewerConfiguration#getReconciler(ISourceViewer) */ public IReconciler getReconciler(ISourceViewer sourceViewer) { if (getEditor() != null && getEditor().isEditable()) { MonoReconciler reconciler= new MonoReconciler(new JavaReconcilingStrategy(getEditor()), false); reconciler.setDelay(500); return reconciler; } return null; } /* * @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String) */ public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) { if (JavaPartitionScanner.JAVA_DOC.equals(contentType) || JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType)) return new JavaDocAutoIndentStrategy(); return new JavaAutoIndentStrategy(); } /* * @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String) */ public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { if (JavaPartitionScanner.JAVA_DOC.equals(contentType) || JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType) || JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT.equals(contentType)) return new DefaultTextDoubleClickStrategy(); return new JavaDoubleClickSelector(); } /* * @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String) */ public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) { return new String[] { "//", "" }; } /* * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String) */ public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) { return new String[] {"\t", " ", ""}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /* * @see SourceViewerConfiguration#getTabWidth(ISourceViewer) */ public int getTabWidth(ISourceViewer sourceViewer) { return 4; } /* * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) */ public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { return new JavaAnnotationHover(); } /* * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) */ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { return new JavaTextHover(getEditor()); } /* * @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer) */ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { return new String[] { IDocument.DEFAULT_CONTENT_TYPE, JavaPartitionScanner.JAVA_DOC, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT }; } /* * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer) */ public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { ContentFormatter formatter= new ContentFormatter(); IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer); formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE); formatter.enablePartitionAwareFormatting(false); formatter.setPartitionManagingPositionCategories(fJavaTextTools.getPartitionManagingPositionCategories()); return formatter; } /* * @see SourceViewerConfiguration#getHoverControlCreator(ISourceViewer) */ public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) { return getInformationControlCreator(sourceViewer, true); } private IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer, final boolean cutDown) { return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); return new DefaultInformationControl(parent, style, new HTMLTextPresenter(cutDown)); // return new HoverBrowserControl(parent); } }; } /* * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) */ public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) { InformationPresenter presenter= new InformationPresenter(getInformationControlCreator(sourceViewer, false)); IInformationProvider provider= new JavaInformationProvider(getEditor()); presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE); presenter.setInformationProvider(provider, JavaPartitionScanner.JAVA_DOC); presenter.setSizeConstraints(60, 10, true, true); return presenter; } }
6,322
Bug 6322 All types dialog shows obfuscated classes
JDK 1.4 includes obfuscated classes (a, a1, b, c, d) etc. This classes show up prominently in the Open Type dialog. They should be less prominent. Options: a) sort lower case class names after the ones that start with a capital letter b) filter them out completly. I suggest to a)
verified fixed
b87b856
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T15:36:28Z"
"2001-11-26T18:40:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/FilteredList.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jdt.internal.core.Assert; import org.eclipse.jdt.internal.ui.util.StringMatcher; /** * A composite widget which holds a list of elements for user selection. * The elements are sorted alphabetically. * Optionally, the elements can be filtered and duplicate entries can * be hidden (folding). */ public class FilteredList extends Composite { public interface FilterMatcher { /** * Sets the filter. * * @param pattern the filter pattern. * @param ignoreCase a flag indicating whether pattern matching is case insensitive or not. * @param ignoreWildCards a flag indicating whether wildcard characters are interpreted or not. */ void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards); /** * Returns <code>true</code> if the object matches the pattern, <code>false</code> otherwise. * <code>setFilter()</code> must have been called at least once prior to a call to this method. */ boolean match(Object element); } private class DefaultFilterMatcher implements FilterMatcher { private StringMatcher fMatcher; public void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards) { fMatcher= new StringMatcher(pattern + '*', ignoreCase, ignoreWildCards); } public boolean match(Object element) { return fMatcher.match(fRenderer.getText(element)); } } private Table fList; private ILabelProvider fRenderer; private boolean fMatchEmtpyString= true; private boolean fIgnoreCase; private boolean fAllowDuplicates; private String fFilter= ""; //$NON-NLS-1$ private TwoArrayQuickSorter fSorter; private Object[] fElements= new Object[0]; private Label[] fLabels; private Vector fImages= new Vector(); private int[] fFoldedIndices; private int fFoldedCount; private int[] fFilteredIndices; private int fFilteredCount; private FilterMatcher fFilterMatcher= new DefaultFilterMatcher(); private static class Label { public final String string; public final Image image; public Label(String string, Image image) { this.string= string; this.image= image; } public boolean equals(Label label) { if (label == null) return false; return string.equals(label.string) && image.equals(label.image); } } private class LabelComparator implements Comparator { private boolean fIgnoreCase; LabelComparator(boolean ignoreCase) { fIgnoreCase= ignoreCase; } public int compare(Object left, Object right) { Label leftLabel= (Label) left; Label rightLabel= (Label) right; int value= fIgnoreCase ? leftLabel.string.compareToIgnoreCase(rightLabel.string) : leftLabel.string.compareTo(rightLabel.string); if (value != 0) return value; // images are allowed to be null if (leftLabel.image == null) { return (rightLabel.image == null) ? 0 : -1; } else if (rightLabel.image == null) { return +1; } else { return fImages.indexOf(leftLabel.image) - fImages.indexOf(rightLabel.image); } } } /** * Constructs a new instance of a filtered list. * @param parent the parent composite. * @param style the widget style. * @param renderer the label renderer. * @param ignoreCase specifies whether sorting and folding is case sensitive. * @param allowDuplicates specifies whether folding of duplicates is desired. * @param matchEmptyString specifies whether empty filter strings should filter everything or nothing. */ public FilteredList(Composite parent, int style, ILabelProvider renderer, boolean ignoreCase, boolean allowDuplicates, boolean matchEmptyString) { super(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; setLayout(layout); fList= new Table(this, style); fList.setLayoutData(new GridData(GridData.FILL_BOTH)); fList.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { fRenderer.dispose(); } }); fRenderer= renderer; fIgnoreCase= ignoreCase; fSorter= new TwoArrayQuickSorter(new LabelComparator(ignoreCase)); fAllowDuplicates= allowDuplicates; fMatchEmtpyString= matchEmptyString; } /** * Sets the list of elements. * @param elements the elements to be shown in the list. */ public void setElements(Object[] elements) { if (elements == null) { fElements= new Object[0]; } else { // copy list for sorting fElements= new Object[elements.length]; System.arraycopy(elements, 0, fElements, 0, elements.length); } int length= fElements.length; // fill labels fLabels= new Label[length]; Set imageSet= new HashSet(); for (int i= 0; i != length; i++) { String text= fRenderer.getText(fElements[i]); Image image= fRenderer.getImage(fElements[i]); fLabels[i]= new Label(text, image); imageSet.add(image); } fImages.clear(); fImages.addAll(imageSet); fSorter.sort(fLabels, fElements); fFilteredIndices= new int[length]; fFilteredCount= filter(); fFoldedIndices= new int[length]; fFoldedCount= fold(); updateList(); } /** * Tests if the list (before folding and filtering) is empty. * @return returns <code>true</code> if the list is empty, <code>false</code> otherwise. */ public boolean isEmpty() { return (fElements == null) || (fElements.length == 0); } /** * Sets the filter matcher. */ public void setFilterMatcher(FilterMatcher filterMatcher) { Assert.isNotNull(filterMatcher); fFilterMatcher= filterMatcher; } /** * Adds a selection listener to the list. * @param listener the selection listener to be added. */ public void addSelectionListener(SelectionListener listener) { fList.addSelectionListener(listener); } /** * Removes a selection listener from the list. * @param listener the selection listener to be removed. */ public void removeSelectionListener(SelectionListener listener) { fList.removeSelectionListener(listener); } /** * Sets the selection of the list. * @param selection an array of indices specifying the selection. */ public void setSelection(int[] selection) { fList.setSelection(selection); } /** * Returns the selection of the list. * @return returns an array of indices specifying the current selection. */ public int[] getSelectionIndices() { return fList.getSelectionIndices(); } /** * Returns the selection of the list. * This is a convenience function for <code>getSelectionIndices()</code>. * @return returns the index of the selection, -1 for no selection. */ public int getSelectionIndex() { return fList.getSelectionIndex(); } /** * Sets the selection of the list. * @param elements the array of elements to be selected. */ public void setSelection(Object[] elements) { if ((elements == null) || (fElements == null)) return; // fill indices int[] indices= new int[elements.length]; for (int i= 0; i != elements.length; i++) { int j; for (j= 0; j != fFoldedCount; j++) { int max= (j == fFoldedCount - 1) ? fFilteredCount : fFoldedIndices[j + 1]; int l; for (l= fFoldedIndices[j]; l != max; l++) { // found matching element? if (fElements[fFilteredIndices[l]].equals(elements[i])) { indices[i]= j; break; } } if (l != max) break; } // not found if (j == fFoldedCount) indices[i] = 0; } fList.setSelection(indices); } /** * Returns an array of the selected elements. The type of the elements * returned in the list are the same as the ones passed with * <code>setElements</code>. The array does not contain the rendered strings. * @return returns the array of selected elements. */ public Object[] getSelection() { if (fList.isDisposed() || (fList.getSelectionCount() == 0)) return new Object[0]; int[] indices= fList.getSelectionIndices(); Object[] elements= new Object[indices.length]; for (int i= 0; i != indices.length; i++) elements[i]= fElements[fFilteredIndices[fFoldedIndices[indices[i]]]]; return elements; } /** * Sets the filter pattern. Current only prefix filter patterns are supported. * @param filter the filter pattern. */ public void setFilter(String filter) { fFilter= (filter == null) ? "" : filter; //$NON-NLS-1$ fFilteredCount= filter(); fFoldedCount= fold(); updateList(); } /** * Returns the filter pattern. * @return returns the filter pattern. */ public String getFilter() { return fFilter; } /** * Returns all elements which are folded together to one entry in the list. * @param index the index selecting the entry in the list. * @return returns an array of elements folded together, <code>null</code> if index is out of range. */ public Object[] getFoldedElements(int index) { if ((index < 0) || (index >= fFoldedCount)) return null; int start= fFoldedIndices[index]; int count= (index == fFoldedCount - 1) ? fFilteredCount - start : fFoldedIndices[index + 1] - start; Object[] elements= new Object[count]; for (int i= 0; i != count; i++) elements[i]= fElements[fFilteredIndices[start + i]]; return elements; } /* * Folds duplicate entries. Two elements are considered as a pair of * duplicates if they coiincide in the rendered string and image. * @return returns the number of elements after folding. */ private int fold() { if (fAllowDuplicates) { for (int i= 0; i != fFilteredCount; i++) fFoldedIndices[i]= i; // identity mapping return fFilteredCount; } else { int k= 0; Label last= null; for (int i= 0; i != fFilteredCount; i++) { int j= fFilteredIndices[i]; Label current= fLabels[j]; if (! current.equals(last)) { fFoldedIndices[k]= i; k++; last= current; } } return k; } } /* * Filters the list with the filter pattern. * @return returns the number of elements after filtering. */ private int filter() { if (((fFilter == null) || (fFilter.length() == 0)) && !fMatchEmtpyString) return 0; fFilterMatcher.setFilter(fFilter.trim(), fIgnoreCase, false); int k= 0; for (int i= 0; i != fElements.length; i++) { if (fFilterMatcher.match(fElements[i])) fFilteredIndices[k++]= i; } return k; } /* * Updates the list widget. */ private void updateList() { if (fList.isDisposed()) return; fList.setRedraw(false); // resize table int itemCount= fList.getItemCount(); if (fFoldedCount < itemCount) fList.remove(0, itemCount - fFoldedCount - 1); else if (fFoldedCount > itemCount) for (int i= 0; i != fFoldedCount - itemCount; i++) new TableItem(fList, SWT.NONE); // fill table TableItem[] items= fList.getItems(); for (int i= 0; i != fFoldedCount; i++) { TableItem item= items[i]; Label label= fLabels[fFilteredIndices[fFoldedIndices[i]]]; item.setText(label.string); item.setImage(label.image); } // select first item if any if (fList.getItemCount() > 0) fList.setSelection(0); fList.setRedraw(true); fList.notifyListeners(SWT.Selection, new Event()); } }
6,322
Bug 6322 All types dialog shows obfuscated classes
JDK 1.4 includes obfuscated classes (a, a1, b, c, d) etc. This classes show up prominently in the Open Type dialog. They should be less prominent. Options: a) sort lower case class names after the ones that start with a capital letter b) filter them out completly. I suggest to a)
verified fixed
b87b856
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T15:36:28Z"
"2001-11-26T18:40:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TypeSelectionDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.util.AllTypesSearchEngine; import org.eclipse.jdt.internal.ui.util.StringMatcher; import org.eclipse.jdt.internal.ui.util.TypeInfo; import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider; /** * A dialog to select a type from a list of types. */ public class TypeSelectionDialog extends TwoPaneElementSelector { private static class TypeFilterMatcher implements FilteredList.FilterMatcher { private StringMatcher fMatcher; private StringMatcher fQualifierMatcher; /* * @see FilteredList.FilterMatcher#setFilter(String, boolean) */ public void setFilter(String pattern, boolean ignoreCase, boolean igoreWildCards) { int qualifierIndex= pattern.lastIndexOf("."); //$NON-NLS-1$ // type if (qualifierIndex == -1) { fQualifierMatcher= null; fMatcher= new StringMatcher(pattern + '*', ignoreCase, igoreWildCards); // qualified type } else { fQualifierMatcher= new StringMatcher(pattern.substring(0, qualifierIndex), ignoreCase, igoreWildCards); fMatcher= new StringMatcher(pattern.substring(qualifierIndex + 1), ignoreCase, igoreWildCards); } } /* * @see FilteredList.FilterMatcher#match(Object) */ public boolean match(Object element) { if (!(element instanceof TypeInfo)) return false; TypeInfo type= (TypeInfo) element; if (!fMatcher.match(type.getTypeName())) return false; if (fQualifierMatcher == null) return true; return fQualifierMatcher.match(type.getTypeContainerName()); } } private IRunnableContext fRunnableContext; private IJavaSearchScope fScope; private int fStyle; /** * Constructs a type selection dialog. * @param parent the parent shell. * @param context the runnable context. * @param scope the java search scope. * @param style the widget style. */ public TypeSelectionDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style) { super(parent, new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeInfoLabelProvider.SHOW_ROOT_POSTFIX)); Assert.isNotNull(context); Assert.isNotNull(scope); fRunnableContext= context; fScope= scope; fStyle= style; setUpperListLabel(JavaUIMessages.getString("TypeSelectionDialog.upperLabel")); //$NON-NLS-1$ setLowerListLabel(JavaUIMessages.getString("TypeSelectionDialog.lowerLabel")); //$NON-NLS-1$ } public void create() { if (getFilter() == null) setFilter("A"); //$NON-NLS-1$ super.create(); } /* * @see AbstractElementListSelectionDialog#createFilteredList(Composite) */ protected FilteredList createFilteredList(Composite parent) { FilteredList list= super.createFilteredList(parent); fFilteredList.setFilterMatcher(new TypeFilterMatcher()); return list; } /** * @see Window#open() */ public int open() { AllTypesSearchEngine engine= new AllTypesSearchEngine(JavaPlugin.getWorkspace()); List typeList= engine.searchTypes(fRunnableContext, fScope, fStyle); if (typeList.isEmpty()) { String title= JavaUIMessages.getString("TypeSelectionDialog.notypes.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.notypes.message"); //$NON-NLS-1$ MessageDialog.openInformation(getShell(), title, message); return CANCEL; } TypeInfo[] typeRefs= (TypeInfo[])typeList.toArray(new TypeInfo[typeList.size()]); setElements(typeRefs); return super.open(); } /** * @see SelectionStatusDialog#computeResult() */ protected void computeResult() { TypeInfo ref= (TypeInfo) getLowerSelectedElement(); if (ref == null) return; try { IType type= ref.resolveType(fScope); if (type == null) { // not a class file or compilation unit String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); setResult(null); } else { List result= new ArrayList(1); result.add(type); setResult(result); } } catch (JavaModelException e) { String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); setResult(null); } } }
6,062
Bug 6062 JavaDocCompletionProcessor should be have configurable case sensitivity
Need implementation of the following JavaDocCompletionProcessor method public void restrictProposalsToMatchingCases(boolean restrict.
resolved fixed
0114a08
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T17:30:16Z"
"2001-11-19T14:26:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/CompletionEvaluator.java
package org.eclipse.jdt.internal.ui.text.javadoc; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.ArrayList; import java.util.List; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.java.ResultCollector; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; public class CompletionEvaluator { protected final static String[] fgTagProposals= { "@author", //$NON-NLS-1$ "@deprecated", //$NON-NLS-1$ "@exception", //$NON-NLS-1$ "@link", //$NON-NLS-1$ "@param", //$NON-NLS-1$ "@return", //$NON-NLS-1$ "@see", "@serial", "@serialData", "@serialField", "@since", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "@throws", //$NON-NLS-1$ "@version" //$NON-NLS-1$ }; protected final static String[] fgHTMLProposals= { "<code>", "</code>", //$NON-NLS-2$ //$NON-NLS-1$ "<br>", //$NON-NLS-1$ "<b>", "</b>", //$NON-NLS-2$ //$NON-NLS-1$ "<i>", "</i>", //$NON-NLS-2$ //$NON-NLS-1$ "<pre>", "</pre>" //$NON-NLS-2$ //$NON-NLS-1$ }; private ICompilationUnit fCompilationUnit; private IDocument fDocument; private int fCurrentPos; private int fCurrentLength; private JavaElementLabelProvider fLabelProvider; private List fResult; public CompletionEvaluator(ICompilationUnit cu, IDocument doc, int pos, int length) { fCompilationUnit= cu; fDocument= doc; fCurrentPos= pos; fCurrentLength= length; fResult= new ArrayList(); fLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_POST_QUALIFIED | JavaElementLabelProvider.SHOW_PARAMETERS); } private static boolean isWordPart(char ch) { return Character.isJavaIdentifierPart(ch) || (ch == '#') || (ch == '.') || (ch == '/'); } private static int findCharBeforeWord(IDocument doc, int lineBeginPos, int pos) { int currPos= pos - 1; if (currPos > lineBeginPos) { try { while (currPos > lineBeginPos && isWordPart(doc.getChar(currPos))) { currPos--; } return currPos; } catch (BadLocationException e) { } } return pos; } private static int findLastWhitespace(IDocument doc, int lineBeginPos, int pos) { try { int currPos= pos - 1; while (currPos >= lineBeginPos && Character.isWhitespace(doc.getChar(currPos))) { currPos--; } return currPos + 1; } catch (BadLocationException e) { } return pos; } private static int findClosingCharacter(IDocument doc, int pos, int end, char endChar) throws BadLocationException { int curr= pos; while (curr < end && (doc.getChar(curr) != endChar)) { curr++; } if (curr < end) { return curr + 1; } return pos; } private static int findReplaceEndPos(IDocument doc, String newText, String oldText, int pos) { if (oldText.length() == 0 || oldText.equals(newText)) { return pos; } try { IRegion lineInfo= doc.getLineInformationOfOffset(pos); int end= lineInfo.getOffset() + lineInfo.getLength(); if (newText.endsWith(">")) { //$NON-NLS-1$ // for html, search the tag end character return findClosingCharacter(doc, pos, end, '>'); } else { char ch= 0; int pos1= pos; while (pos1 < end && Character.isJavaIdentifierPart(ch= doc.getChar(pos1))) { pos1++; } if (pos1 < end) { // for method references, search the closing bracket if ((ch == '(') && newText.endsWith(")")) { //$NON-NLS-1$ return findClosingCharacter(doc, pos1, end, ')'); } } return pos1; } } catch (BadLocationException e) { e.printStackTrace(); } return pos; } public ICompletionProposal[] computeProposals() throws JavaModelException { evalProposals(); ICompletionProposal[] res= new ICompletionProposal[fResult.size()]; fResult.toArray(res); fResult.clear(); return res; } private void evalProposals() throws JavaModelException { try { IRegion info= fDocument.getLineInformationOfOffset(fCurrentPos); int lineBeginPos= info.getOffset(); int word1Begin= findCharBeforeWord(fDocument, lineBeginPos, fCurrentPos); if (word1Begin == fCurrentPos) { return; } char firstChar= fDocument.getChar(word1Begin); if (firstChar == '@') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgTagProposals, JavaPluginImages.IMG_OBJS_JAVADOCTAG); return; } else if (firstChar == '<') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgHTMLProposals, JavaPluginImages.IMG_OBJS_HTMLTAG); return; } else if (!Character.isWhitespace(firstChar)) { return; } String prefix= fDocument.get(word1Begin + 1, fCurrentPos - word1Begin - 1); // could be a composed java doc construct (@param, @see ...) int word2End= findLastWhitespace(fDocument, lineBeginPos, word1Begin); if (word2End != lineBeginPos) { // find the word before the prefix int word2Begin= findCharBeforeWord(fDocument, lineBeginPos, word2End); if (fDocument.getChar(word2Begin) == '@') { String tag= fDocument.get(word2Begin, word2End - word2Begin); if (addArgumentProposals(tag, prefix)) { return; } } } addAllTags(prefix); } catch (BadLocationException e) { // ignore } } private void addAllTags(String prefix) { String jdocPrefix= "@" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgTagProposals.length; i++) { String curr= fgTagProposals[i]; if (curr.startsWith(jdocPrefix)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG), null)); } } String htmlPrefix= "<" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgHTMLProposals.length; i++) { String curr= fgHTMLProposals[i]; if (curr.startsWith(htmlPrefix)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_HTMLTAG), null)); } } } private void addProposals(String prefix, String[] choices, String imageName) { for (int i= 0; i < choices.length; i++) { String curr= choices[i]; if (curr.startsWith(prefix)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(imageName), null)); } } } private void addProposals(String prefix, IJavaElement[] choices) { for (int i= 0; i < choices.length; i++) { IJavaElement elem= choices[i]; String curr= getReplaceString(elem); if (curr.startsWith(prefix)) { String info= getProposalInfo(elem); fResult.add(createCompletion(curr, prefix, fLabelProvider.getText(elem), fLabelProvider.getImage(elem), info)); } } } private String getProposalInfo(IJavaElement elem) { if (elem instanceof IMember) { try { return JavaDocAccess.getJavaDocText((IMember)elem); } catch (JavaModelException e) { JavaPlugin.getDefault().log(e.getStatus()); } } return null; } private String getReplaceString(IJavaElement elem) { if (elem instanceof IMethod) { IMethod meth= (IMethod)elem; StringBuffer buf= new StringBuffer(); buf.append(meth.getElementName()); buf.append('('); String[] types= meth.getParameterTypes(); int last= types.length - 1; for (int i= 0; i <= last; i++) { buf.append(Signature.toString(types[i])); if (i != last) { buf.append(", "); //$NON-NLS-1$ } } buf.append(')'); return buf.toString(); } else { return elem.getElementName(); } } /** * Returns true if case is handeled */ private boolean addArgumentProposals(String tag, String argument) throws JavaModelException { if ("@see".equals(tag) || "@link".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$ evalSeeTag(argument); return true; } else if ("@param".equals(tag)) { //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IMethod) { String[] names= ((IMethod)elem).getParameterNames(); addProposals(argument, names, JavaPluginImages.IMG_MISC_DEFAULT); } return true; } else if ("@throws".equals(tag) || "@exception".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IMethod) { String[] exceptions= ((IMethod)elem).getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { String curr= Signature.toString(exceptions[i]); if (curr.startsWith(argument)) { fResult.add(createCompletion(curr, argument, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS), null)); } } } return true; } else if ("@serialData".equals(tag)) { //$NON-NLS-1$ IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (elem instanceof IField) { String name= ((IField)elem).getElementName(); fResult.add(createCompletion(name, argument, name, fLabelProvider.getImage(elem), null)); } return true; } return false; } private void evalSeeTag(String arg) throws JavaModelException { int wordStart= fCurrentPos - arg.length(); int pidx= arg.indexOf('#'); if (pidx == -1) { ICompletionProposal[] completions= getTypeNameCompletion(wordStart); if (completions != null) { for (int i= 0; i < completions.length; i++) { fResult.add(completions[i]); } } } else { IType parent= null; if (pidx > 0) { // method or field parent= getTypeNameResolve(wordStart, wordStart + pidx); } else { // '@see #foo' IJavaElement elem= fCompilationUnit.getElementAt(wordStart); if (elem != null) { parent= (IType)JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE); } } if (parent != null) { int nidx= arg.indexOf('(', pidx); if (nidx == -1) { nidx= arg.length(); } String prefix= arg.substring(pidx + 1, nidx); addProposals(prefix, parent.getMethods()); addProposals(prefix, parent.getFields()); } } } private ICompletionProposal[] getTypeNameCompletion(int wordStart) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(wordStart, fCurrentPos); if (preparedCU != null) { ResultCollector collector= new ResultCollector(); collector.reset(fCurrentPos, fCompilationUnit.getJavaProject(), fCompilationUnit); try { preparedCU.codeComplete(fCurrentPos, collector); } finally { preparedCU.destroy(); } return collector.getResults(); } return null; } private IType getTypeNameResolve(int wordStart, int wordEnd) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(wordStart, wordEnd); if (preparedCU != null) { try { IJavaElement[] elements= preparedCU.codeSelect(wordStart, wordEnd - wordStart); if (elements != null && elements.length == 1 && elements[0] instanceof IType) { return (IType) elements[0]; } } finally { preparedCU.getBuffer().setContents(fCompilationUnit.getBuffer().getCharacters()); preparedCU.destroy(); } } return null; } private ICompilationUnit createPreparedCU(int wordStart, int wordEnd) throws JavaModelException { IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if (!(elem instanceof ISourceReference)) { return null; } int startpos= ((ISourceReference)elem).getSourceRange().getOffset(); // 1GEYJ5Z: ITPJUI:WINNT - smoke120: code assist in @see tag can result data loss char[] content= (char[]) fCompilationUnit.getBuffer().getCharacters().clone(); if (wordStart < content.length) { for (int i= startpos; i < wordStart; i++) { content[i]= ' '; } } if (wordEnd + 2 < content.length) { // XXX: workaround for 1GAVL08 content[wordEnd]= ' '; content[wordEnd + 1]= 'x'; } ICompilationUnit cu= fCompilationUnit; if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } ICompilationUnit newCU= (ICompilationUnit) cu.getWorkingCopy(); newCU.getBuffer().setContents(content); return newCU; } private ICompletionProposal createCompletion(String newText, String oldText, String labelText, Image image, String info) { int offset= fCurrentPos - oldText.length(); int length= fCurrentLength + oldText.length(); if (fCurrentLength == 0) length= findReplaceEndPos(fDocument, newText, oldText, fCurrentPos) - offset; return new CompletionProposal(newText, offset, length, newText.length(), image, labelText, null, info); } }
6,062
Bug 6062 JavaDocCompletionProcessor should be have configurable case sensitivity
Need implementation of the following JavaDocCompletionProcessor method public void restrictProposalsToMatchingCases(boolean restrict.
resolved fixed
0114a08
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T17:30:16Z"
"2001-11-19T14:26:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocCompletionProcessor.java
package org.eclipse.jdt.internal.ui.text.javadoc; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Arrays; import java.util.Comparator; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.template.TemplateContext; import org.eclipse.jdt.internal.ui.text.template.TemplateEngine; /** * Simple Java doc completion processor. */ public class JavaDocCompletionProcessor implements IContentAssistProcessor { private static class CompletionProposalComparator implements Comparator { public int compare(Object o1, Object o2) { ICompletionProposal c1= (ICompletionProposal) o1; ICompletionProposal c2= (ICompletionProposal) o2; return c1.getDisplayString().compareTo(c2.getDisplayString()); } }; private IEditorPart fEditor; private IWorkingCopyManager fManager; private char[] fProposalAutoActivationSet; private Comparator fComparator; private TemplateEngine fTemplateEngine; public JavaDocCompletionProcessor(IEditorPart editor) { fEditor= editor; fManager= JavaPlugin.getDefault().getWorkingCopyManager(); fTemplateEngine= new TemplateEngine(TemplateContext.JAVADOC); } /** * Tells this processor to order the proposals alphabetically. * * @param order <code>true</code> if proposals should be ordered. */ public void orderProposalsAlphabetically(boolean order) { fComparator= order ? new CompletionProposalComparator() : null; } /** * Tells this processor to restrict is proposals to those * starting with matching cases. * * @param restrict <code>true</code> if proposals should be restricted */ public void restrictProposalsToMatchingCases(boolean restrict) { // not yet supported } /** * @see IContentAssistProcessor#getErrorMessage() */ public String getErrorMessage() { return null; } /** * @see IContentAssistProcessor#getContextInformationValidator() */ public IContextInformationValidator getContextInformationValidator() { return null; } /** * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() */ public char[] getContextInformationAutoActivationCharacters() { return null; } /** * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() */ public char[] getCompletionProposalAutoActivationCharacters() { return fProposalAutoActivationSet; } /** * Sets this processor's set of characters triggering the activation of the * completion proposal computation. * * @param activationSet the activation set */ public void setCompletionProposalAutoActivationCharacters(char[] activationSet) { fProposalAutoActivationSet= activationSet; } /** * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) */ public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { return null; } /** * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) */ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { ICompilationUnit unit= fManager.getWorkingCopy(fEditor.getEditorInput()); IDocument document= viewer.getDocument(); ICompletionProposal[] results= new ICompletionProposal[0]; try { if (unit != null) { int offset= documentOffset; int length= 0; Point selection= viewer.getSelectedRange(); if (selection.y > 0) { offset= selection.x; length= selection.y; } CompletionEvaluator evaluator= new CompletionEvaluator(unit, document, offset, length); results= evaluator.computeProposals(); } } catch (JavaModelException x) { } try { fTemplateEngine.reset(); fTemplateEngine.complete(viewer, documentOffset, unit); } catch (JavaModelException x) { } ICompletionProposal[] templateResults= fTemplateEngine.getResults(); // concatenate arrays ICompletionProposal[] total= new ICompletionProposal[results.length + templateResults.length]; System.arraycopy(templateResults, 0, total, 0, templateResults.length); System.arraycopy(results, 0, total, templateResults.length, results.length); /* * Order here and not in result collector to make sure that the order * applies to all proposals and not just those of the compilation unit. */ return order(total); } /** * Order the given proposals. */ private ICompletionProposal[] order(ICompletionProposal[] proposals) { if (fComparator != null) Arrays.sort(proposals, fComparator); return proposals; } }
6,356
Bug 6356 Outliner has to delete actions
Product version: smoke test for integration build 20011127 - load compilation unit into Java editor - open context menu in outliner observe: there are two delete actions
verified fixed
7f801b9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-27T18:41:06Z"
"2001-11-27T16:53:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; import org.eclipse.jdt.internal.ui.actions.OpenHierarchyPerspectiveItem; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.DeleteAction; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementSorter; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * The content outline page of the Java editor. The viewer implements a proprietary * update mechanism based on Java model deltas. It does not react on domain changes. * It is specified to show the content of ICompilationUnits and IClassFiles. */ class JavaOutlinePage extends Page implements IContentOutlinePage { /** * The element change listener of the java outline viewer. * @see IElementChangedListener */ class ElementChangedListener implements IElementChangedListener { public void elementChanged(final ElementChangedEvent e) { Display d= getControl().getDisplay(); if (d != null) { d.asyncExec(new Runnable() { public void run() { IJavaElementDelta delta= findElement( (ICompilationUnit) fInput, e.getDelta()); if (delta != null && fOutlineViewer != null) { fOutlineViewer.reconcile(delta); } } }); } } protected IJavaElementDelta findElement(ICompilationUnit unit, IJavaElementDelta delta) { if (delta == null || unit == null) return null; IJavaElement element= delta.getElement(); if (unit.equals(element)) return delta; if (element.getElementType() > IJavaElement.CLASS_FILE) return null; IJavaElementDelta[] children= delta.getAffectedChildren(); if (children == null || children.length == 0) return null; for (int i= 0; i < children.length; i++) { IJavaElementDelta d= findElement(unit, children[i]); if (d != null) return d; } return null; } }; /** * Content provider for the children of an ICompilationUnit or * an IClassFile * @see ITreeContentProvider */ class ChildrenProvider implements ITreeContentProvider { private ElementChangedListener fListener; private JavaOutlineErrorTickUpdater fErrorTickUpdater; protected boolean matches(IJavaElement element) { if (element.getElementType() == IJavaElement.METHOD) { String name= element.getElementName(); return (name != null && name.indexOf('<') >= 0); } return false; } protected IJavaElement[] filter(IJavaElement[] children) { boolean initializers= false; for (int i= 0; i < children.length; i++) { if (matches(children[i])) { initializers= true; break; } } if (!initializers) return children; Vector v= new Vector(); for (int i= 0; i < children.length; i++) { if (matches(children[i])) continue; v.addElement(children[i]); } IJavaElement[] result= new IJavaElement[v.size()]; v.copyInto(result); return result; } public Object[] getChildren(Object parent) { if (parent instanceof IParent) { IParent c= (IParent) parent; try { return filter(c.getChildren()); } catch (JavaModelException x) { JavaPlugin.getDefault().logErrorStatus(JavaEditorMessages.getString("JavaOutlinePage.error.ChildrenProvider.getChildren.message1"), x.getStatus()); //$NON-NLS-1$ } } return new Object[0]; } public Object[] getElements(Object parent) { return getChildren(parent); } public Object getParent(Object child) { if (child instanceof IJavaElement) { IJavaElement e= (IJavaElement) child; return e.getParent(); } return null; } public boolean hasChildren(Object parent) { if (parent instanceof IParent) { IParent c= (IParent) parent; try { IJavaElement[] children= filter(c.getChildren()); return (children != null && children.length > 0); } catch (JavaModelException x) { JavaPlugin.getDefault().logErrorStatus(JavaEditorMessages.getString("JavaOutlinePage.error.ChildrenProvider.hasChildren.message1"), x.getStatus()); //$NON-NLS-1$ } } return false; } public boolean isDeleted(Object o) { return false; } public void dispose() { if (fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; } if (fErrorTickUpdater != null) { fErrorTickUpdater.setAnnotationModel(null); fErrorTickUpdater= null; } } /** * @see IContentProvider#inputChanged(Viewer, Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { boolean isCU= (newInput instanceof ICompilationUnit); if (isCU && fListener == null) { fListener= new ElementChangedListener(); JavaCore.addElementChangedListener(fListener); fErrorTickUpdater= new JavaOutlineErrorTickUpdater(fOutlineViewer); fErrorTickUpdater.setAnnotationModel(fEditor.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput())); } else if (isCU && fErrorTickUpdater != null) { fErrorTickUpdater.setAnnotationModel(fEditor.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput())); } else if (!isCU && fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; fErrorTickUpdater.setAnnotationModel(null); fErrorTickUpdater= null; } } }; class JavaOutlineViewer extends TreeViewer { /** * Indicates an item which has been reused. At the point of * its reuse it has been expanded. This field is used to * communicate between <code>internalExpandToLevel</code> and * <code>reuseTreeItem</code>. */ private Item fReusedExpandedItem; public JavaOutlineViewer(Tree tree) { super(tree); setAutoExpandLevel(ALL_LEVELS); } /** * Investigates the given element change event and if affected incrementally * updates the outline. */ public void reconcile(IJavaElementDelta delta) { if (getSorter() == null) { Widget w= findItem(fInput); if (w != null) update(w, delta); } else { // just for now refresh(); } } /** * @see TreeViewer#internalExpandToLevel */ protected void internalExpandToLevel(Widget node, int level) { if (node instanceof Item) { Item i= (Item) node; if (i.getData() instanceof IJavaElement) { IJavaElement je= (IJavaElement) i.getData(); if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) { if (i != fReusedExpandedItem) { setExpanded(i, false); return; } } } } super.internalExpandToLevel(node, level); } protected void reuseTreeItem(Item item, Object element) { // remove children Item[] c= getChildren(item); if (c != null && c.length > 0) { if (getExpanded(item)) fReusedExpandedItem= item; for (int k= 0; k < c.length; k++) { if (c[k].getData() != null) disassociate(c[k]); c[k].dispose(); } } updateItem(item, element); updatePlus(item, element); internalExpandToLevel(item, ALL_LEVELS); fReusedExpandedItem= null; } /** * @see TreeViewer#createTreeItem */ protected void createTreeItem(Widget parent, Object element, int ix) { Item[] children= getChildren(parent); boolean expand= (parent instanceof Item && (children == null || children.length == 0)); Item item= newItem(parent, SWT.NULL, ix); updateItem(item, element); updatePlus(item, element); if (expand) setExpanded((Item) parent, true); internalExpandToLevel(item, ALL_LEVELS); } protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) { if (element instanceof IMethod) { if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { try { return JavaModelUtil.isMainMethod((IMethod)element); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } return "main".equals(element.getElementName()); //$NON-NLS-1$ } return false; } protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException { if (element instanceof IMember) return ((IMember) element).getNameRange(); if (element instanceof ISourceReference) return ((ISourceReference) element).getSourceRange(); return null; } protected boolean overlaps(ISourceRange range, int start, int end) { return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end; } protected boolean filtered(IJavaElement parent, IJavaElement child) { Object[] result= new Object[] { child }; ViewerFilter[] filters= getFilters(); for (int i= 0; i < filters.length; i++) { result= filters[i].filter(this, parent, result); if (result.length == 0) return true; } return false; } protected void update(Widget w, IJavaElementDelta delta) { Item item; Object element; IJavaElement parent= delta.getElement(); IJavaElementDelta[] affected= delta.getAffectedChildren(); Item[] children= getChildren(w); boolean doUpdateParent= false; Vector deletions= new Vector(); Vector additions= new Vector(); go1: for (int i= 0; i < children.length; i++) { item= children[i]; element= item.getData(); for (int j= 0; j < affected.length; j++) { IJavaElement affectedElement= affected[j].getElement(); int status= affected[j].getKind(); if (affectedElement.equals(element)) { // removed if ((status & IJavaElementDelta.REMOVED) != 0) { deletions.addElement(item); doUpdateParent= doUpdateParent || mustUpdateParent(affected[j], affectedElement); continue go1; } // changed if ((status & IJavaElementDelta.CHANGED) != 0) { int change= affected[j].getFlags(); doUpdateParent= doUpdateParent || mustUpdateParent(affected[j], affectedElement); if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { if (filtered(parent, affectedElement)) deletions.addElement(item); else updateItem(item, affectedElement); } if ((change & IJavaElementDelta.F_CONTENT) != 0) updateItem(item, affectedElement); if ((change & IJavaElementDelta.F_CHILDREN) != 0) update(item, affected[j]); continue go1; } } else { // changed if ((status & IJavaElementDelta.CHANGED) != 0 && (affected[j].getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 && !filtered(parent, affectedElement)) additions.addElement(affected[j]); } } } // find all elements to add IJavaElementDelta[] add= delta.getAddedChildren(); if (additions.size() > 0) { IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()]; System.arraycopy(add, 0, tmp, 0, add.length); for (int i= 0; i < additions.size(); i++) tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i); add= tmp; } // add at the right position go2: for (int i= 0; i < add.length; i++) { try { IJavaElement e= add[i].getElement(); if (filtered(parent, e)) continue go2; doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e); ISourceRange rng= getSourceRange(e); int start= rng.getOffset(); int end= start + rng.getLength() - 1; Item last= null; item= null; children= getChildren(w); for (int j= 0; j < children.length; j++) { item= children[j]; IJavaElement r= (IJavaElement) item.getData(); if (r == null) { // parent node collapsed and not be opened before -> do nothing continue go2; } try { rng= getSourceRange(r); if (overlaps(rng, start, end)) { // be tolerant if the delta is not correct, or if // the tree has been updated other than by a delta reuseTreeItem(item, e); continue go2; } else if (rng.getOffset() > start) { if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, (Object) e); } else { // nothing to reuse createTreeItem(w, (Object) e, j); } continue go2; } } catch (JavaModelException x) { // stumbled over deleted element } last= item; } // add at the end of the list if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, e); } else { // nothing to reuse createTreeItem(w, e, -1); } } catch (JavaModelException x) { // the element to be added is not present -> don't add it } } // remove items which haven't been reused Enumeration e= deletions.elements(); while (e.hasMoreElements()) { item= (Item) e.nextElement(); disassociate(item); item.dispose(); } if (doUpdateParent) updateItem(w, delta.getElement()); } }; class LexicalSortingAction extends Action { private JavaElementSorter fSorter= new JavaElementSorter(); public LexicalSortingAction() { super(); setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$ valueChanged(checked, false); } public void run() { valueChanged(isChecked(), true); } private void valueChanged(boolean on, boolean store) { setChecked(on); fOutlineViewer.setSorter(on ? fSorter : null); setToolTipText(on ? JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip.checked") : JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip.unchecked")); //$NON-NLS-2$ //$NON-NLS-1$ setDescription(on ? JavaEditorMessages.getString("JavaOutlinePage.Sort.description.checked") : JavaEditorMessages.getString("JavaOutlinePage.Sort.description.unchecked")); //$NON-NLS-2$ //$NON-NLS-1$ if (store) JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$ } }; class FieldFilter extends ViewerFilter { public boolean select(Viewer viewer, Object parentElement, Object element) { return !(element instanceof IField); } }; class VisibilityFilter extends ViewerFilter { public final static int PUBLIC= 0; public final static int PROTECTED= 1; public final static int PRIVATE= 2; public final static int DEFAULT= 3; public final static int NOT_STATIC= 4; private int fVisibility; public VisibilityFilter(int visibility) { fVisibility= visibility; } /* * 1GEWBY4: ITPJUI:ALL - filtering incorrect on interfaces. */ private boolean belongsToInterface(IMember member) { IType type= member.getDeclaringType(); if (type != null) { try { return type.isInterface(); } catch (JavaModelException x) { // ignore } } return false; } public boolean select(Viewer viewer, Object parentElement, Object element) { if ( !(element instanceof IMember)) return true; if (element instanceof IType) { IType type= (IType) element; IJavaElement parent= type.getParent(); if (parent == null) return true; int elementType= parent.getElementType(); if (elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.CLASS_FILE) return true; } IMember member= (IMember) element; try { int flags= member.getFlags(); switch (fVisibility) { case PUBLIC: /* 1GEWBY4: ITPJUI:ALL - filtering incorrect on interfaces */ return Flags.isPublic(flags) || belongsToInterface(member); case PROTECTED: return Flags.isProtected(flags); case PRIVATE: return Flags.isPrivate(flags); case DEFAULT: { /* 1GEWBY4: ITPJUI:ALL - filtering incorrect on interfaces */ boolean dflt= !(Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)); return dflt ? !belongsToInterface(member) : dflt; } case NOT_STATIC: return !Flags.isStatic(flags); } } catch (JavaModelException x) { } // unreachable return false; } }; class FilterAction extends Action { private ViewerFilter fFilter; private String fCheckedDesc; private String fUncheckedDesc; private String fCheckedTooltip; private String fUncheckedTooltip; private String fPreferenceKey; public FilterAction(ViewerFilter filter, String label, String checkedDesc, String uncheckedDesc, String checkedTooltip, String uncheckedTooltip, String prefKey) { super(); fFilter= filter; setText(label); fCheckedDesc= checkedDesc; fUncheckedDesc= uncheckedDesc; fCheckedTooltip= checkedTooltip; fUncheckedTooltip= uncheckedTooltip; fPreferenceKey= prefKey; boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean(fPreferenceKey); valueChanged(checked, false); } public void run() { valueChanged(isChecked(), true); } private void valueChanged(boolean on, boolean store) { setChecked(on); if (on) { fOutlineViewer.addFilter(fFilter); setToolTipText(fCheckedTooltip); setDescription(fCheckedDesc); } else { fOutlineViewer.removeFilter(fFilter); setToolTipText(fUncheckedTooltip); setDescription(fUncheckedDesc); } if (store) JavaPlugin.getDefault().getPreferenceStore().setValue(fPreferenceKey, on); } }; private IJavaElement fInput; private String fContextMenuID; private Menu fMenu; private JavaOutlineViewer fOutlineViewer; private JavaEditor fEditor; private ListenerList fSelectionChangedListeners= new ListenerList(); private Hashtable fActions= new Hashtable(); private ContextMenuGroup[] fActionGroups; public JavaOutlinePage(String contextMenuID, JavaEditor editor) { super(); Assert.isNotNull(editor); fContextMenuID= contextMenuID; fEditor= editor; } private void fireSelectionChanged(ISelection selection) { SelectionChangedEvent event= new SelectionChangedEvent(this, selection); Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; ++i) ((ISelectionChangedListener) listeners[i]).selectionChanged(event); } /** * @see IPage#createControl */ public void createControl(Composite parent) { Tree tree= new Tree(parent, SWT.MULTI); JavaElementLabelProvider lprovider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_PARAMETERS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_TYPE); fOutlineViewer= new JavaOutlineViewer(tree); fOutlineViewer.setContentProvider(new ChildrenProvider()); fOutlineViewer.setLabelProvider(lprovider); MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { contextMenuAboutToShow(manager); } }); fMenu= manager.createContextMenu(tree); tree.setMenu(fMenu); fActionGroups= new ContextMenuGroup[] { new GenerateGroup(), new JavaSearchGroup(), new ReorgGroup() }; fOutlineViewer.setInput(fInput); fOutlineViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent e) { fireSelectionChanged(e.getSelection()); } }); fOutlineViewer.getControl().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } }); } public void dispose() { if (fEditor == null) return; fEditor.outlinePageClosed(); fEditor= null; Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; i++) fSelectionChangedListeners.remove(listeners[i]); fSelectionChangedListeners= null; if (fMenu != null && !fMenu.isDisposed()) { fMenu.dispose(); fMenu= null; } super.dispose(); } public Control getControl() { if (fOutlineViewer != null) return fOutlineViewer.getControl(); return null; } public void setInput(IJavaElement inputElement) { fInput= inputElement; if (fOutlineViewer != null) fOutlineViewer.setInput(fInput); } public void select(ISourceReference reference) { if (fOutlineViewer != null) { ISelection s= StructuredSelection.EMPTY; if (reference != null) s= new StructuredSelection(reference); fOutlineViewer.setSelection(s, true); } } public void setAction(String actionID, IAction action) { Assert.isNotNull(actionID); if (action == null) fActions.remove(actionID); else fActions.put(actionID, action); } public IAction getAction(String actionID) { Assert.isNotNull(actionID); return (IAction) fActions.get(actionID); } /** * Convenience method to add the action installed under the given actionID to the * specified group of the menu. */ protected void addAction(IMenuManager menu, String group, String actionID) { IAction action= getAction(actionID); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (action.isEnabled()) { IMenuManager subMenu= menu.findMenuUsingPath(group); if (subMenu != null) subMenu.add(action); else menu.appendToGroup(group, action); } } } private void addRefactoring(IMenuManager menu){ MenuManager refactoring= new MenuManager(JavaEditorMessages.getString("JavaOutlinePage.ContextMenu.refactoring.label")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fOutlineViewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void addOpenPerspectiveItem(IMenuManager menu) { ISelection s= getSelection(); if (s.isEmpty() || ! (s instanceof IStructuredSelection)) return; IStructuredSelection selection= (IStructuredSelection)s; if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IType)) return; IType[] input= {(IType)element}; // XXX should get the workbench window form the PartSite IWorkbenchWindow w= JavaPlugin.getActiveWorkbenchWindow(); menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, new OpenHierarchyPerspectiveItem(w, input)); } protected void contextMenuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); if (OrganizeImportsAction.canActionBeAdded(getSelection())) { addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "OrganizeImports"); //$NON-NLS-1$ } addAction(menu, IContextMenuConstants.GROUP_OPEN, "OpenImportDeclaration"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_OPEN, "OpenSuperImplementation"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_SHOW, "ShowInPackageView"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "DeleteElement"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "ReplaceWithEdition"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "AddEdition"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_ADDITIONS, "AddMethodEntryBreakpoint"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_ADDITIONS, "AddWatchpoint"); //$NON_NLS-1$ ContextMenuGroup.add(menu, fActionGroups, fOutlineViewer); addRefactoring(menu); addOpenPerspectiveItem(menu); } /** * @see Page#setFocus() */ public void setFocus() { if (fOutlineViewer != null) fOutlineViewer.getControl().setFocus(); } /** * @see Page#makeContributions(IMenuManager, IToolBarManager, IStatusLineManager) */ public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { if (statusLineManager != null) { StatusBarUpdater updater= new StatusBarUpdater(statusLineManager); addSelectionChangedListener(updater); } Action action= new LexicalSortingAction(); toolBarManager.add(action); action= new FilterAction(new FieldFilter(), JavaEditorMessages.getString("JavaOutlinePage.HideFields.label"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.description.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.description.unchecked"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.tooltip.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.tooltip.unchecked"), "HideFields.isChecked"); //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(action, "fields_co.gif"); //$NON-NLS-1$ toolBarManager.add(action); action= new FilterAction(new VisibilityFilter(VisibilityFilter.NOT_STATIC), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.label"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.description.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.description.unchecked"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.tooltip.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.tooltip.unchecked"), "HideStaticMembers.isChecked"); //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(action, "static_co.gif"); //$NON-NLS-1$ toolBarManager.add(action); action= new FilterAction(new VisibilityFilter(VisibilityFilter.PUBLIC), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.label"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.description.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.description.unchecked"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.tooltip.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.tooltip.unchecked"), "HideNonePublicMembers.isChecked"); //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(action, "public_co.gif"); //$NON-NLS-1$ toolBarManager.add(action); } /** * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) */ public void addSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.add(listener); } /** * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.remove(listener); } /** * @see ISelectionProvider#getSelection() */ public ISelection getSelection() { if (fOutlineViewer == null) return StructuredSelection.EMPTY; return fOutlineViewer.getSelection(); } /** * @see ISelectionProvider#setSelection(ISelection) */ public void setSelection(ISelection selection) { if (fOutlineViewer != null) fOutlineViewer.setSelection(selection); } /** * Checkes whether a given Java element is an inner type. */ private boolean isInnerType(IJavaElement element) { if (element.getElementType() == IJavaElement.TYPE) { IJavaElement parent= element.getParent(); int type= parent.getElementType(); return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE); } return false; } /** * Handles key events in viewer. */ private void handleKeyPressed(KeyEvent event) { if (event.stateMask != 0) return; IAction action= null; if (event.character == SWT.DEL) { action= getAction("DeleteElement"); //$NON-NLS-1$ if (action instanceof DeleteAction){ //special case - DeleteAction is not a ISelectionChangedListener DeleteAction deleteAction= (DeleteAction)action; deleteAction.update(); if (deleteAction.isEnabled()) deleteAction.run(); return; } } else if (event.keyCode == SWT.F4) { // Special case since Open Type Hierarchy is no action. OpenTypeHierarchyUtil.open(getSelection(), fEditor.getSite().getWorkbenchWindow()); } if (action != null && action.isEnabled()) action.run(); } }
6,375
Bug 6375 Organize imports asks to specify the same class
Perform 'organize imports' against a class that has import javax.naming.* in it, and has 2 jars on the classpath that both contain javax.naming.InitialContext. You will get a dialog asking which type to import. In the list, you will see 'javax.naming.InitialContext' twice in the list. Can change 'Organize imports' so that it recognizes that these are the same package/class and does NOT prompt the user to choose between the same class?
resolved fixed
0acbfa2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-28T19:03:27Z"
"2001-11-28T06:46:40Z"
org.eclipse.jdt.ui/core
6,375
Bug 6375 Organize imports asks to specify the same class
Perform 'organize imports' against a class that has import javax.naming.* in it, and has 2 jars on the classpath that both contain javax.naming.InitialContext. You will get a dialog asking which type to import. In the list, you will see 'javax.naming.InitialContext' twice in the list. Can change 'Organize imports' so that it recognizes that these are the same package/class and does NOT prompt the user to choose between the same class?
resolved fixed
0acbfa2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-28T19:03:27Z"
"2001-11-28T06:46:40Z"
extension/org/eclipse/jdt/internal/corext/codegeneration/OrganizeImportsOperation.java
5,225
Bug 5225 1.0 -- Casting problem in RunToLineAction class
The Java editor fails to open a java source file when we have PICLDebugTargets in the debug view. There is java.lang.ClassCastException at org.eclipse.jdt.internal.ui.javaeditor.RunToLineAction.getContextFromModel (RunToLineAction.java:111) The getContextFromModel() method incorrectly assumes that all debug targets are of type JDIDebugTarget. I see a few other spots in RunToLineAction where a debug target is blindly cast to a JDIDebugTarget without checking it first. I am seeing this with the R1.0 (0.137 build) driver. I don't think this is a new problem.
verified fixed
e66d704
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T03:18:23Z"
"2001-10-24T21:46:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/RunToLineAction.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.core.runtime.IStatus; import org.eclipse.debug.core.*; import org.eclipse.debug.core.model.*; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jdt.core.*; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.debug.core.JDIDebugTarget; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.*; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.IUpdate; /** * Action to support run to line (i.e. where the cursor is) */ public class RunToLineAction extends Action implements IUpdate { protected JavaEditor fEditor; public RunToLineAction(JavaEditor editor) { super(); setText(JavaEditorMessages.getString("RunToLine.label")); //$NON-NLS-1$ setToolTipText(JavaEditorMessages.getString("RunToLine.tooltip")); //$NON-NLS-1$ setDescription(JavaEditorMessages.getString("RunToLine.description")); //$NON-NLS-1$ fEditor= editor; update(); WorkbenchHelp.setHelp(this, new Object[] { IJavaHelpContextIds.RUN_TO_LINE_ACTION }); } public void run() { try { JDIDebugTarget target= getContext(); if (target == null) { fEditor.getSite().getShell().getDisplay().beep(); return; } ISelectionProvider sp= fEditor.getSelectionProvider(); if (sp == null) { return; } ITextSelection ts= (ITextSelection) sp.getSelection(); int lineNumber= ts.getStartLine() + 1; IJavaElement je= (IJavaElement) fEditor.getElementAt(ts.getOffset()); IType type= null; if (je instanceof IType) { type= (IType) je; } else if (je instanceof IMember) { type= ((IMember) je).getDeclaringType(); } if (type == null) { return; } IBreakpoint breakpoint= null; try { breakpoint= JDIDebugModel.createRunToLineBreakpoint(type, lineNumber, -1, -1); } catch (DebugException de) { errorDialog(de.getStatus()); return; } target.breakpointAdded(breakpoint); IThread[] threads= target.getThreads(); for (int i= 0; i < threads.length; i++) { IThread thread= threads[i]; if (thread.canResume()) { try { thread.resume(); } catch (DebugException de) { } break; } } } catch(DebugException de) { } } /** * Resolves the debug target context to set the run to line */ protected JDIDebugTarget getContext() throws DebugException{ JDIDebugTarget target= getContextFromUI(); if (target == null) { target= getContextFromModel(); } if (target == null) { return null; } IThread[] threads= target.getThreads(); boolean threadSuspended= false; for (int i= 0; i < threads.length; i++) { IThread thread= threads[i]; if (thread.canResume()) { threadSuspended=true; break; } } if (threadSuspended) { return target; } return null; } /** * Resolves a debug target context from the model */ protected JDIDebugTarget getContextFromModel() throws DebugException { IDebugTarget[] dts= DebugPlugin.getDefault().getLaunchManager().getDebugTargets(); for (int i= 0; i < dts.length; i++) { JDIDebugTarget dt= (JDIDebugTarget)dts[i]; if (getContextFromDebugTarget(dt) != null) { return dt; } } return null; } /** * Resolves a debug target context from the model */ protected JDIDebugTarget getContextFromThread(IThread thread) throws DebugException { if (thread.isSuspended()) { return (JDIDebugTarget) thread.getDebugTarget(); } return null; } /** * Resolves a stack frame context from the UI */ protected JDIDebugTarget getContextFromUI() throws DebugException { IWorkbenchPage page= fEditor.getSite().getWorkbenchWindow().getActivePage(); if (page == null) return null; IViewPart part= page.findView(IDebugUIConstants.ID_DEBUG_VIEW); if (part == null) return null; ISelectionProvider sp= part.getSite().getSelectionProvider(); if (sp != null) { ISelection s= sp.getSelection(); if (s instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection) s; Object item= ss.getFirstElement(); if (item instanceof IStackFrame) { return (JDIDebugTarget) ((IStackFrame) item).getDebugTarget(); } if (item instanceof IThread) { return getContextFromThread((IThread) item); } if (item instanceof JDIDebugTarget) { return (JDIDebugTarget) item; } } } return null; } protected void errorDialog(IStatus status) { Shell shell= fEditor.getSite().getShell(); ErrorDialog.openError(shell, JavaEditorMessages.getString("RunToLine.error.title1"), JavaEditorMessages.getString("RunToLine.error.message1"), status); //$NON-NLS-1$ //$NON-NLS-2$ } /** * @see IUpdate */ public void update() { try { setEnabled(getContext() != null); } catch (DebugException de) { setEnabled(false); JavaPlugin.log(de.getStatus()); } } /** * Resolves a stack frame context from the model */ protected JDIDebugTarget getContextFromDebugTarget(JDIDebugTarget dt) throws DebugException { if (dt.isTerminated() || dt.isDisconnected()) { return null; } IThread[] threads= dt.getThreads(); for (int i= 0; i < threads.length; i++) { IThread thread= threads[i]; if (thread.isSuspended()) { return dt; } } return null; } }
5,677
Bug 5677 Hierarchy outline has empty space
I opened a hierarchy view on IActionDelegate. Selected a few of the subinterfaces, changed the expansion state of the tree. Then, no matter which item I selected in the top window (the hierarchy tree), the bottom window (the outline table) always had exactly four empty rows before the first item was listed.
resolved fixed
e23f1fe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T11:25:18Z"
"2001-11-08T20:06:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/MethodsViewer.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IMemento; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; import org.eclipse.jdt.internal.ui.actions.OpenJavaElementAction; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementSorter; import org.eclipse.jdt.internal.ui.viewsupport.MarkerErrorTickProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemItemMapper; /** * Method viewer shows a list of methods of a input type. * Offers filter actions. * No dependency to the type hierarchy view */ public class MethodsViewer extends TableViewer implements IProblemChangedListener { private ProblemItemMapper fProblemItemMapper; /** * Sorter that uses the unmodified labelprovider (No declaring class names) */ private static class MethodsViewerSorter extends JavaElementSorter { public MethodsViewerSorter() { } public int compare(Viewer viewer, Object e1, Object e2) { int cat1 = category(e1); int cat2 = category(e2); if (cat1 != cat2) return cat1 - cat2; // cat1 == cat2 String name1= JavaElementLabels.getElementLabel((IJavaElement) e1, JavaElementLabels.ALL_DEFAULT); String name2= JavaElementLabels.getElementLabel((IJavaElement) e2, JavaElementLabels.ALL_DEFAULT); return getCollator().compare(name1, name2); } } private static final String TAG_HIDEFIELDS= "hidefields"; //$NON-NLS-1$ private static final String TAG_HIDESTATIC= "hidestatic"; //$NON-NLS-1$ private static final String TAG_HIDENONPUBLIC= "hidenonpublic"; //$NON-NLS-1$ private static final String TAG_SHOWINHERITED= "showinherited"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "mv_vertical_scroll"; //$NON-NLS-1$ private MethodsViewerFilterAction[] fFilterActions; private MethodsViewerFilter fFilter; private OpenJavaElementAction fOpen; private TableColumn fTableColumn; private ShowInheritedMembersAction fShowInheritedMembersAction; private ContextMenuGroup[] fStandardGroups; public MethodsViewer(Composite parent, IWorkbenchPart part) { super(new Table(parent, SWT.MULTI)); fProblemItemMapper= new ProblemItemMapper(); fTableColumn= new TableColumn(getTable(), SWT.NULL | SWT.MULTI | SWT.FULL_SELECTION); getTable().addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { adjustTableColumnSize(); } }); JavaElementLabelProvider lprovider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); lprovider.setErrorTickManager(new MarkerErrorTickProvider()); MethodsContentProvider contentProvider= new MethodsContentProvider(); setLabelProvider(lprovider); setContentProvider(contentProvider); fOpen= new OpenJavaElementAction(this); addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { fOpen.run(); } }); fFilter= new MethodsViewerFilter(); // fields String title= TypeHierarchyMessages.getString("MethodsViewer.hide_fields.label"); //$NON-NLS-1$ String helpContext= IJavaHelpContextIds.FILTER_FIELDS_ACTION; MethodsViewerFilterAction hideFields= new MethodsViewerFilterAction(this, title, MethodsViewerFilter.FILTER_FIELDS, helpContext, false); hideFields.setDescription(TypeHierarchyMessages.getString("MethodsViewer.hide_fields.description")); //$NON-NLS-1$ hideFields.setToolTipChecked(TypeHierarchyMessages.getString("MethodsViewer.hide_fields.tooltip.checked")); //$NON-NLS-1$ hideFields.setToolTipUnchecked(TypeHierarchyMessages.getString("MethodsViewer.hide_fields.tooltip.unchecked")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$ // static title= TypeHierarchyMessages.getString("MethodsViewer.hide_static.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_STATIC_ACTION; MethodsViewerFilterAction hideStatic= new MethodsViewerFilterAction(this, title, MethodsViewerFilter.FILTER_STATIC, helpContext, false); hideStatic.setDescription(TypeHierarchyMessages.getString("MethodsViewer.hide_static.description")); //$NON-NLS-1$ hideStatic.setToolTipChecked(TypeHierarchyMessages.getString("MethodsViewer.hide_static.tooltip.checked")); //$NON-NLS-1$ hideStatic.setToolTipUnchecked(TypeHierarchyMessages.getString("MethodsViewer.hide_static.tooltip.unchecked")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$ // non-public title= TypeHierarchyMessages.getString("MethodsViewer.hide_nonpublic.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_PUBLIC_ACTION; MethodsViewerFilterAction hideNonPublic= new MethodsViewerFilterAction(this, title, MethodsViewerFilter.FILTER_NONPUBLIC, helpContext, false); hideNonPublic.setDescription(TypeHierarchyMessages.getString("MethodsViewer.hide_nonpublic.description")); //$NON-NLS-1$ hideNonPublic.setToolTipChecked(TypeHierarchyMessages.getString("MethodsViewer.hide_nonpublic.tooltip.checked")); //$NON-NLS-1$ hideNonPublic.setToolTipUnchecked(TypeHierarchyMessages.getString("MethodsViewer.hide_nonpublic.tooltip.unchecked")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$ // order corresponds to order in toolbar fFilterActions= new MethodsViewerFilterAction[] { hideFields, hideStatic, hideNonPublic }; addFilter(fFilter); fShowInheritedMembersAction= new ShowInheritedMembersAction(this, false); showInheritedMethods(false); fStandardGroups= new ContextMenuGroup[] { new JavaSearchGroup(), new GenerateGroup() }; setSorter(new MethodsViewerSorter()); } /** * Show inherited methods */ public void showInheritedMethods(boolean on) { MethodsContentProvider cprovider= (MethodsContentProvider) getContentProvider(); try { cprovider.showInheritedMethods(on); fShowInheritedMembersAction.setChecked(on); JavaElementLabelProvider lprovider= (JavaElementLabelProvider) getLabelProvider(); if (on) { lprovider.turnOn(JavaElementLabelProvider.SHOW_POST_QUALIFIED); } else { lprovider.turnOff(JavaElementLabelProvider.SHOW_POST_QUALIFIED); } refresh(); adjustTableColumnSize(); } catch (JavaModelException e) { ExceptionHandler.handle(e, getControl().getShell(), TypeHierarchyMessages.getString("MethodsViewer.toggle.error.title"), TypeHierarchyMessages.getString("MethodsViewer.toggle.error.message")); //$NON-NLS-2$ //$NON-NLS-1$ } } private void adjustTableColumnSize() { if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } } /* * @see Viewer#inputChanged(Object, Object) */ protected void inputChanged(Object input, Object oldInput) { super.inputChanged(input, oldInput); adjustTableColumnSize(); } /** * Returns <code>true</code> if inherited methods are shown. */ public boolean isShowInheritedMethods() { return ((MethodsContentProvider) getContentProvider()).isShowInheritedMethods(); } /** * Filters the method list */ public void setMemberFilter(int filterProperty, boolean set) { if (set) { fFilter.addFilter(filterProperty); } else { fFilter.removeFilter(filterProperty); } for (int i= 0; i < fFilterActions.length; i++) { if (fFilterActions[i].getFilterProperty() == filterProperty) { fFilterActions[i].setChecked(set); } } refresh(); } /** * Returns <code>true</code> if the given filter is set. */ public boolean hasMemberFilter(int filterProperty) { return fFilter.hasFilter(filterProperty); } /** * Saves the state of the filter actions */ public void saveState(IMemento memento) { memento.putString(TAG_HIDEFIELDS, String.valueOf(hasMemberFilter(MethodsViewerFilter.FILTER_FIELDS))); memento.putString(TAG_HIDESTATIC, String.valueOf(hasMemberFilter(MethodsViewerFilter.FILTER_STATIC))); memento.putString(TAG_HIDENONPUBLIC, String.valueOf(hasMemberFilter(MethodsViewerFilter.FILTER_NONPUBLIC))); memento.putString(TAG_SHOWINHERITED, String.valueOf(isShowInheritedMethods())); ScrollBar bar= getTable().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_VERTICAL_SCROLL, String.valueOf(position)); } /** * Restores the state of the filter actions */ public void restoreState(IMemento memento) { boolean set= Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)).booleanValue(); setMemberFilter(MethodsViewerFilter.FILTER_FIELDS, set); set= Boolean.valueOf(memento.getString(TAG_HIDESTATIC)).booleanValue(); setMemberFilter(MethodsViewerFilter.FILTER_STATIC, set); set= Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)).booleanValue(); setMemberFilter(MethodsViewerFilter.FILTER_NONPUBLIC, set); set= Boolean.valueOf(memento.getString(TAG_SHOWINHERITED)).booleanValue(); showInheritedMethods(set); ScrollBar bar= getTable().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } } /** * Attaches a contextmenu listener to the table */ public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) { MenuManager menuMgr= new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(menuListener); Menu menu= menuMgr.createContextMenu(getTable()); getTable().setMenu(menu); viewSite.registerContextMenu(popupId, menuMgr, this); } /** * Fills up the context menu with items for the method viewer * Should be called by the creator of the context menu */ public void contributeToContextMenu(IMenuManager menu) { if (fOpen.canActionBeAdded()) { menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen); } ContextMenuGroup.add(menu, fStandardGroups, this); } /** * Fills up the tool bar with items for the method viewer * Should be called by the creator of the tool bar */ public void contributeToToolBar(ToolBarManager tbm) { tbm.add(fShowInheritedMembersAction); tbm.add(new Separator()); tbm.add(fFilterActions[0]); // fields tbm.add(fFilterActions[1]); // static tbm.add(fFilterActions[2]); // public } /* * @see IProblemChangedListener#problemsChanged */ public void problemsChanged(final Set changed) { Control control= getControl(); if (control != null && !control.isDisposed()) { control.getDisplay().asyncExec(new Runnable() { public void run() { fProblemItemMapper.problemsChanged(changed, (ILabelProvider)getLabelProvider()); } }); } } /* * @see StructuredViewer#associate(Object, Item) */ protected void associate(Object element, Item item) { if (item.getData() != element) { fProblemItemMapper.addToMap(element, item); } super.associate(element, item); } /* * @see StructuredViewer#disassociate(Item) */ protected void disassociate(Item item) { fProblemItemMapper.removeFromMap(item.getData(), item); super.disassociate(item); } }
5,677
Bug 5677 Hierarchy outline has empty space
I opened a hierarchy view on IActionDelegate. Selected a few of the subinterfaces, changed the expansion state of the tree. Then, no matter which item I selected in the top window (the hierarchy tree), the bottom window (the outline table) always had exactly four empty rows before the first item was listed.
resolved fixed
e23f1fe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T11:25:18Z"
"2001-11-08T20:06:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Table; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.TableViewer; /** * A list with checkboxes and a button bat. Typical buttons are 'Check All' and 'Uncheck All'. * List model is independend of widget creation. * DialogFields controls are: Label, List and Composite containing buttons. */ public class CheckedListDialogField extends ListDialogField { private int fCheckAllButtonIndex; private int fUncheckAllButtonIndex; private List fCheckElements; public CheckedListDialogField(IListAdapter adapter, String[] customButtonLabels, ILabelProvider lprovider) { super(adapter, customButtonLabels, lprovider); fCheckElements= new ArrayList(); fCheckAllButtonIndex= -1; fUncheckAllButtonIndex= -1; } /** * Sets the index of the 'check' button in the button label array passed in the constructor. * The behaviour of the button marked as the check button will then be handled internally. * (enable state, button invocation behaviour) */ public void setCheckAllButtonIndex(int checkButtonIndex) { Assert.isTrue(checkButtonIndex < fButtonLabels.length); fCheckAllButtonIndex= checkButtonIndex; } /** * Sets the index of the 'uncheck' button in the button label array passed in the constructor. * The behaviour of the button marked as the uncheck button will then be handled internally. * (enable state, button invocation behaviour) */ public void setUncheckAllButtonIndex(int uncheckButtonIndex) { Assert.isTrue(uncheckButtonIndex < fButtonLabels.length); fUncheckAllButtonIndex= uncheckButtonIndex; } /* * @see ListDialogField#createTableViewer */ protected TableViewer createTableViewer(Composite parent) { Table table= new Table(parent, SWT.CHECK + getListStyle()); CheckboxTableViewer tableViewer= new CheckboxTableViewer(table); tableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent e) { doCheckStateChanged(e); } }); return tableViewer; } /* * @see ListDialogField#getListControl */ public Control getListControl(Composite parent) { Control control= super.getListControl(parent); if (parent != null) { ((CheckboxTableViewer)fTable).setCheckedElements(fCheckElements.toArray()); } return control; } /* * @see DialogField#dialogFieldChanged * Hooks in to get element changes to update check model. */ public void dialogFieldChanged() { for (int i= fCheckElements.size() -1; i >= 0; i--) { if (!fElements.contains(fCheckElements.get(i))) { fCheckElements.remove(i); } } super.dialogFieldChanged(); } private void checkStateChanged() { //call super and do not update check model super.dialogFieldChanged(); } /** * Gets the checked elements. */ public List getCheckedElements() { return new ArrayList(fCheckElements); } /** * Returns true if the element is checked. */ public boolean isChecked(Object obj) { return fCheckElements.contains(obj); } /** * Sets the checked elements. */ public void setCheckedElements(List list) { fCheckElements= new ArrayList(list); if (fTable != null) { ((CheckboxTableViewer)fTable).setCheckedElements(list.toArray()); } checkStateChanged(); } /** * Sets the checked state of an element. */ public void setChecked(Object object, boolean state) { setCheckedWithoutUpdate(object, state); checkStateChanged(); } /** * Sets the checked state of an element. no dialog changed listener informed */ public void setCheckedWithoutUpdate(Object object, boolean state) { if (!fCheckElements.contains(object)) { fCheckElements.add(object); } if (fTable != null) { ((CheckboxTableViewer)fTable).setChecked(object, state); } } /** * Sets the check state of all elements */ public void checkAll(boolean state) { if (state) { fCheckElements= getElements(); } else { fCheckElements.clear(); } if (fTable != null) { ((CheckboxTableViewer)fTable).setAllChecked(state); } checkStateChanged(); } private void doCheckStateChanged(CheckStateChangedEvent e) { if (e.getChecked()) { fCheckElements.add(e.getElement()); } else { fCheckElements.remove(e.getElement()); } checkStateChanged(); } // ------ enable / disable management /* * @see ListDialogField#getManagedButtonState */ protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fCheckAllButtonIndex) { return !fElements.isEmpty(); } else if (index == fUncheckAllButtonIndex) { return !fElements.isEmpty(); } return super.getManagedButtonState(sel, index); } /* * @see ListDialogField#extraButtonPressed */ protected boolean managedButtonPressed(int index) { if (index == fCheckAllButtonIndex) { checkAll(true); } else if (index == fUncheckAllButtonIndex) { checkAll(false); } else { return super.managedButtonPressed(index); } return true; } }
5,677
Bug 5677 Hierarchy outline has empty space
I opened a hierarchy view on IActionDelegate. Selected a few of the subinterfaces, changed the expansion state of the tree. Then, no matter which item I selected in the top window (the hierarchy tree), the bottom window (the outline table) always had exactly four empty rows before the first item was listed.
resolved fixed
e23f1fe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T11:25:18Z"
"2001-11-08T20:06:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; 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.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ColumnWeightData; 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.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; /** * A list with a button bar. * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. * List model is independend of widget creation. * DialogFields controls are: Label, List and Composite containing buttons. */ public class ListDialogField extends DialogField { protected TableViewer fTable; protected ILabelProvider fLabelProvider; protected ListViewerAdapter fListViewerAdapter; protected List fElements; protected ViewerSorter fViewerSorter; protected String[] fButtonLabels; private Button[] fButtonControls; private boolean[] fButtonsEnabled; private int fRemoveButtonIndex; private int fUpButtonIndex; private int fDownButtonIndex; private Label fLastSeparator; private Table fTableControl; private Composite fButtonsControl; private ISelection fSelectionWhenEnabled; private TableColumn fTableColumn; private IListAdapter fListAdapter; private Object fParentElement; /** * Creates the <code>ListDialogField</code>. * @param adapter A listener for button invocation, selection changes. * @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and * marks a separator. * @param lprovider The label provider to render the table entries */ public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) { super(); fListAdapter= adapter; fLabelProvider= lprovider; fListViewerAdapter= new ListViewerAdapter(); fParentElement= this; fElements= new ArrayList(10); fButtonLabels= buttonLabels; if (fButtonLabels != null) { int nButtons= fButtonLabels.length; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsEnabled[i]= true; } } fTable= null; fTableControl= null; fButtonsControl= null; fRemoveButtonIndex= -1; fUpButtonIndex= -1; fDownButtonIndex= -1; } /** * Sets the index of the 'remove' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'remove' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); fRemoveButtonIndex= removeButtonIndex; } /** * Sets the index of the 'up' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'up' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); fUpButtonIndex= upButtonIndex; } /** * Sets the index of the 'down' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'down' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); fDownButtonIndex= downButtonIndex; } /** * Sets the viewerSorter. * @param viewerSorter The viewerSorter to set */ public void setViewerSorter(ViewerSorter viewerSorter) { fViewerSorter= viewerSorter; } // ------ adapter communication private void buttonPressed(int index) { if (!managedButtonPressed(index)) { fListAdapter.customButtonPressed(this, index); } } /** * Checks if the button pressed is handled internally * @return Returns true if button has been handled. */ protected boolean managedButtonPressed(int index) { if (index == fRemoveButtonIndex) { remove(); } else if (index == fUpButtonIndex) { up(); } else if (index == fDownButtonIndex) { down(); } else { return false; } return true; } // ------ layout helpers /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); Label label= getLabelControl(parent); MGridData gd= gridDataForLabel(1); gd.verticalAlignment= gd.BEGINNING; label.setLayoutData(gd); Control list= getListControl(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= true; gd.grabColumn= 0; gd.horizontalSpan= nColumns - 2; gd.widthHint= SWTUtil.convertWidthInCharsToPixels(50, list); gd.heightHint= SWTUtil.convertHeightInCharsToPixels(6, list); list.setLayoutData(gd); Composite buttons= getButtonBox(parent); gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= gd.FILL; gd.grabExcessVerticalSpace= false; gd.horizontalSpan= 1; buttons.setLayoutData(gd); return new Control[] { label, list, buttons }; } /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { return 3; } /** * Sets the minimal width of the buttons. Must be called after widget creation. */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { ((MGridData)fLastSeparator.getLayoutData()).widthHint= minWidth; } } // ------ ui creation /** * Returns the list control. When called the first time, the control will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Control getListControl(Composite parent) { if (fTableControl == null) { assertCompositeNotNull(parent); fTable= createTableViewer(parent); fTable.setContentProvider(fListViewerAdapter); fTable.setLabelProvider(fLabelProvider); fTable.addSelectionChangedListener(fListViewerAdapter); fTableControl= (Table)fTable.getControl(); // Add a table column. TableLayout tableLayout= new TableLayout(); tableLayout.addColumnData(new ColumnWeightData(100)); fTableColumn= new TableColumn(fTableControl, SWT.NONE); fTableColumn.setResizable(false); fTableControl.setLayout(tableLayout); fTable.setInput(fParentElement); if (fViewerSorter != null) { fTable.setSorter(fViewerSorter); } fTableControl.setEnabled(isEnabled()); if (fSelectionWhenEnabled != null) { postSetSelection(fSelectionWhenEnabled); } fTableColumn.getDisplay().asyncExec(new Runnable() { public void run() { if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } } }); } return fTableControl; } /** * Returns the internally used table viewer. */ public TableViewer getTableViewer() { return fTable; } /* * Subclasses may override to specify a different style. */ protected int getListStyle(){ return SWT.BORDER + SWT.MULTI + SWT.H_SCROLL + SWT.V_SCROLL; } protected TableViewer createTableViewer(Composite parent) { Table table= new Table(parent, getListStyle()); return new TableViewer(table); } protected Button createButton(Composite parent, String label, SelectionListener listener) { Button button= new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(listener); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= gd.BEGINNING; gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); return button; } private Label createSeparator(Composite parent) { Label separator= new Label(parent, SWT.NONE); separator.setVisible(false); MGridData gd= new MGridData(); gd.horizontalAlignment= gd.FILL; gd.verticalAlignment= gd.BEGINNING; gd.heightHint= 4; separator.setLayoutData(gd); return separator; } /** * Returns the composite containing the buttons. When called the first time, the control * will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; Composite contents= new Composite(parent, SWT.NULL); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; contents.setLayout(layout); if (fButtonLabels != null) { fButtonControls= new Button[fButtonLabels.length]; for (int i= 0; i < fButtonLabels.length; i++) { String currLabel= fButtonLabels[i]; if (currLabel != null) { fButtonControls[i]= createButton(contents, currLabel, listener); fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); } else { fButtonControls[i]= null; createSeparator(contents); } } } fLastSeparator= createSeparator(contents); updateButtonState(); fButtonsControl= contents; } return fButtonsControl; } private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { for (int i= 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; } } } } // ------ enable / disable management /* * @see DialogField#dialogFieldChanged */ public void dialogFieldChanged() { super.dialogFieldChanged(); if (fTableColumn != null && !fTableColumn.isDisposed()) { fTableColumn.pack(); } updateButtonState(); } private Button getButton(int index) { if (fButtonControls != null && index >= 0 && index < fButtonControls.length) { return fButtonControls[index]; } return null; } /* * Updates the enable state of the all buttons */ protected void updateButtonState() { if (fButtonControls != null) { ISelection sel= fTable.getSelection(); for (int i= 0; i < fButtonControls.length; i++) { Button button= fButtonControls[i]; if (isOkToUse(button)) { boolean extraState= getManagedButtonState(sel, i); button.setEnabled(isEnabled() && extraState && fButtonsEnabled[i]); } } } } protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fRemoveButtonIndex) { return !sel.isEmpty(); } else if (index == fUpButtonIndex) { return !sel.isEmpty() && canMoveUp(); } else if (index == fDownButtonIndex) { return !sel.isEmpty() && canMoveDown(); } return true; } /* * @see DialogField#updateEnableState */ protected void updateEnableState() { super.updateEnableState(); boolean enabled= isEnabled(); if (isOkToUse(fTableControl)) { if (!enabled) { fSelectionWhenEnabled= fTable.getSelection(); selectElements(null); } else { selectElements(fSelectionWhenEnabled); fSelectionWhenEnabled= null; } fTableControl.setEnabled(enabled); } updateButtonState(); } /** * Sets a button enabled or disabled. */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { fButtonsEnabled[index]= enable; updateButtonState(); } } // ------ model access /** * Sets the elements shown in the list. */ public void setElements(List elements) { fElements= new ArrayList(elements); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } /** * Gets the elements shown in the list. * The list returned is a copy, so it can be modified by the user. */ public List getElements() { return new ArrayList(fElements); } /** * Gets the elements shown at the given index. */ public Object getElement(int index) { return fElements.get(index); } /** * Replace an element. */ public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException { int idx= fElements.indexOf(oldElement); if (idx != -1) { if (oldElement.equals(newElement) || fElements.contains(newElement)) { return; } fElements.set(idx, newElement); if (fTable != null) { List selected= getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } fTable.refresh(); selectElements(new StructuredSelection(selected)); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Adds an element at the end of the list. */ public void addElement(Object element) { if (fElements.contains(element)) { return; } fElements.add(element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds elements at the end of the list. */ public void addElements(List elements) { int nElements= elements.size(); if (nElements > 0) { // filter duplicated ArrayList elementsToAdd= new ArrayList(nElements); for (int i= 0; i < nElements; i++) { Object elem= elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); } } fElements.addAll(elementsToAdd); if (fTable != null) { fTable.add(elementsToAdd.toArray()); } dialogFieldChanged(); } } /** * Adds an element at a position. */ public void insertElementAt(Object element, int index) { if (fElements.contains(element)) { return; } fElements.add(index, element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds an element at a position. */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } } /** * Removes an element from the list. */ public void removeElement(Object element) throws IllegalArgumentException { if (fElements.remove(element)) { if (fTable != null) { fTable.remove(element); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Removes elements from the list. */ public void removeElements(List elements) { if (elements.size() > 0) { fElements.removeAll(elements); if (fTable != null) { fTable.remove(elements.toArray()); } dialogFieldChanged(); } } /** * Gets the number of elements */ public int getSize() { return fElements.size(); } public void selectElements(ISelection selection) { fSelectionWhenEnabled= selection; if (fTable != null) { fTable.setSelection(selection, true); } } public void selectFirstElement() { Object element= null; if (fViewerSorter != null) { Object[] arr= fElements.toArray(); fViewerSorter.sort(fTable, arr); if (arr.length > 0) { element= arr[0]; } } else { if (fElements.size() > 0) { element= fElements.get(0); } } if (element != null) { selectElements(new StructuredSelection(element)); } } public void postSetSelection(final ISelection selection) { if (isOkToUse(fTableControl)) { Display d= fTableControl.getDisplay(); d.asyncExec(new Runnable() { public void run() { if (isOkToUse(fTableControl)) { selectElements(selection); } } }); } } /** * Refreshes the table. */ public void refresh() { fTable.refresh(); } // ------- list maintenance private List moveUp(List elements, List move) { int nElements= elements.size(); List res= new ArrayList(nElements); Object floating= null; for (int i= 0; i < nElements; i++) { Object curr= elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } floating= curr; } } if (floating != null) { res.add(floating); } return res; } private void moveUp(List toMoveUp) { if (toMoveUp.size() > 0) { setElements(moveUp(fElements, toMoveUp)); fTable.reveal(toMoveUp.get(0)); } } private void moveDown(List toMoveDown) { if (toMoveDown.size() > 0) { setElements(reverse(moveUp(reverse(fElements), toMoveDown))); fTable.reveal(toMoveDown.get(toMoveDown.size() - 1)); } } private List reverse(List p) { List reverse= new ArrayList(p.size()); for (int i= p.size()-1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; } private void remove() { removeElements(getSelectedElements()); } private void up() { moveUp(getSelectedElements()); } private void down() { moveDown(getSelectedElements()); } private boolean canMoveUp() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); for (int i= 0; i < indc.length; i++) { if (indc[i] != i) { return true; } } } return false; } private boolean canMoveDown() { if (isOkToUse(fTableControl)) { int[] indc= fTableControl.getSelectionIndices(); int k= fElements.size() - 1; for (int i= indc.length - 1; i >= 0 ; i--, k--) { if (indc[i] != k) { return true; } } } return false; } /** * Returns the selected elements. */ public List getSelectedElements() { List result= new ArrayList(); if (fTable != null) { ISelection selection= fTable.getSelection(); if (selection instanceof IStructuredSelection) { Iterator iter= ((IStructuredSelection)selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } } } return result; } // ------- ListViewerAdapter private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener { // ------- ITableContentProvider Interface ------------ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // will never happen } public boolean isDeleted(Object element) { return false; } public void dispose() { } public Object[] getElements(Object obj) { return fElements.toArray(); } // ------- ISelectionChangedListener Interface ------------ public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } } private void doListSelected(SelectionChangedEvent event) { updateButtonState(); if (fListAdapter != null) { fListAdapter.selectionChanged(this); } } }
6,412
Bug 6412 API Request - Package selection dialog including pre-reqs
The Java debugger requires the ability to specify a "pacakge to run in" in the snippet editor. To do this, we use the API on JavaUI to create a package selection dialog for a project. However, we need to be able to choose from packages in pre-req projects/jars as well. Currently the API only specifies packages in a single project.
resolved fixed
a5cfa23
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T15:37:46Z"
"2001-11-29T02:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/IJavaElementSearchConstants.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.ui; /** * Search scope constants for Java selection dialogs. * <p> * This interface declares constants only; it is not intended to be implemented. * </p> * * @see JavaUI */ public interface IJavaElementSearchConstants { /** * Search scope constant (bit mask) indicating that classes should be considered. * Used when opening certain kinds of selection dialogs. */ public static final int CONSIDER_CLASSES= 1 << 1; /** * Search scope constant (bit mask) indicating that interfaces should be considered. * Used when opening certain kinds of selection dialogs. */ public static final int CONSIDER_INTERFACES= 1 << 2; /** * Search scope constant (bit mask) indicating that both classes and interfaces * should be considered. Equivalent to * <code>CONSIDER_CLASSES | CONSIDER_INTERFACES</code>. */ public static final int CONSIDER_TYPES= CONSIDER_CLASSES | CONSIDER_INTERFACES; /** * Search scope constant (bit mask) indicating that binaries should be considered. * Used when opening certain kinds of selection dialogs. */ public static final int CONSIDER_BINARIES= 1 << 3; /** * Search scope constant (bit mask) indicating that external JARs should be considered. * Used when opening certain kinds of selection dialogs. */ public static final int CONSIDER_EXTERNAL_JARS= 1 << 4; }
6,412
Bug 6412 API Request - Package selection dialog including pre-reqs
The Java debugger requires the ability to specify a "pacakge to run in" in the snippet editor. To do this, we use the API on JavaUI to create a package selection dialog for a project. However, we need to be able to choose from packages in pre-req projects/jars as well. Currently the API only specifies packages in a single project.
resolved fixed
a5cfa23
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T15:37:46Z"
"2001-11-29T02:13:20Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaUI.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IProject; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.util.Assert; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.SharedImages; import org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.MainTypeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.MultiMainTypeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.MultiTypeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; /** * Central access point for the Java UI plug-in (id <code>"org.eclipse.jdt.ui"</code>). * This class provides static methods for: * <ul> * <li> creating various kinds of selection dialogs to present a collection * of Java elements to the user and let them make a selection.</li> * <li> opening a Java editor on a compilation unit.</li> * </ul> * <p> * This class provides static methods and fields only; it is not intended to be * instantiated or subclassed by clients. * </p> */ public final class JavaUI { private static ISharedImages fgSharedImages= null; private JavaUI() { // prevent instantiation of JavaUI. } /** * The id of the Java plugin (value <code>"org.eclipse.jdt.ui"</code>). */ public static final String ID_PLUGIN= "org.eclipse.jdt.ui"; //$NON-NLS-1$ /** * The id of the Java perspective * (value <code>"org.eclipse.jdt.ui.JavaPerspective"</code>). */ public static final String ID_PERSPECTIVE= "org.eclipse.jdt.ui.JavaPerspective"; //$NON-NLS-1$ /** * The id of the Java hierarchy perspective * (value <code>"org.eclipse.jdt.ui.JavaHierarchyPerspective"</code>). */ public static final String ID_HIERARCHYPERSPECTIVE= "org.eclipse.jdt.ui.JavaHierarchyPerspective"; //$NON-NLS-1$ /** * The id of the Java action set * (value <code>"org.eclipse.jdt.ui.JavaActionSet"</code>). */ public static final String ID_ACTION_SET= "org.eclipse.jdt.ui.JavaActionSet"; //$NON-NLS-1$ /** * The editor part id of the editor that presents Java compilation units * (value <code>"org.eclipse.jdt.ui.CompilationUnitEditor"</code>). */ public static final String ID_CU_EDITOR= "org.eclipse.jdt.ui.CompilationUnitEditor"; //$NON-NLS-1$ /** * The editor part id of the editor that presents Java binary class files * (value <code>"org.eclipse.jdt.ui.ClassFileEditor"</code>). */ public static final String ID_CF_EDITOR= "org.eclipse.jdt.ui.ClassFileEditor"; //$NON-NLS-1$ /** * The editor part id of the code snippet editor * (value <code>"org.eclipse.jdt.ui.SnippetEditor"</code>). */ public static final String ID_SNIPPET_EDITOR= "org.eclipse.jdt.ui.SnippetEditor"; //$NON-NLS-1$ /** * The view part id of the Packages view * (value <code>"org.eclipse.jdt.ui.PackageExplorer"</code>). * <p> * When this id is used to access * a view part with <code>IWorkbenchPage.findView</code> or * <code>showView</code>, the returned <code>IViewPart</code> * can be safely cast to an <code>IPackagesViewPart</code>. * </p> * * @see IPackagesViewPart * @see org.eclipse.ui.IWorkbenchPage#findView * @see org.eclipse.ui.IWorkbenchPage#showView */ public static final String ID_PACKAGES= "org.eclipse.jdt.ui.PackageExplorer"; //$NON-NLS-1$ /** * The view part id of the type hierarchy part. * (value <code>"org.eclipse.jdt.ui.TypeHierarchy"</code>). * <p> * When this id is used to access * a view part with <code>IWorkbenchPage.findView</code> or * <code>showView</code>, the returned <code>IViewPart</code> * can be safely cast to an <code>ITypeHierarchyViewPart</code>. * </p> * * @see ITypeHierarchyViewPart * @see org.eclipse.ui.IWorkbenchPage#findView * @see org.eclipse.ui.IWorkbenchPage#showView */ public static final String ID_TYPE_HIERARCHY= "org.eclipse.jdt.ui.TypeHierarchy"; //$NON-NLS-1$ /** * The class org.eclipse.debug.core.model.IProcess allows attaching * String properties to processes. The Java UI contributes a property * page for IProcess that will show the contents of the property * with this key. * The intent of this property is to show the command line a process * was launched with. * @deprecated */ public final static String ATTR_CMDLINE= JavaPlugin.getPluginId()+".launcher.cmdLine"; //$NON-NLS-1$ /** * Returns the shared images for the Java UI. * * @return the shared images manager */ public static ISharedImages getSharedImages() { if (fgSharedImages == null) fgSharedImages= new SharedImages(); return fgSharedImages; } /** * Creates a selection dialog that lists all packages of the given Java project. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected packages (of type * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param project the Java project * @param style flags defining the style of the dialog; the only valid flag is * <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, indicating that * packages from binary package fragment roots should be included in addition * to those from source package fragment roots * @param filter the filter * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException { Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES) == IJavaElementSearchConstants.CONSIDER_BINARIES); IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); List consideredRoots= null; if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) { consideredRoots= Arrays.asList(roots); } else { consideredRoots= new ArrayList(roots.length); for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot root= roots[i]; if (root.getKind() != IPackageFragmentRoot.K_BINARY) consideredRoots.add(root); } } int flags= JavaElementLabelProvider.SHOW_DEFAULT; if (consideredRoots.size() > 1) flags= flags | JavaElementLabelProvider.SHOW_ROOT; List packages= new ArrayList(); Iterator iter= consideredRoots.iterator(); while(iter.hasNext()) { IPackageFragmentRoot root= (IPackageFragmentRoot)iter.next(); packages.addAll(Arrays.asList(root.getChildren())); } ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(flags)); dialog.setIgnoreCase(false); dialog.setElements(packages.toArray()); // XXX inefficient dialog.setFilter(filter); return dialog; } /** * @see createPackageDialog(Shell,IJavaProject,int,String) */ public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style) throws JavaModelException { return createPackageDialog(parent, project, style, "A"); //$NON-NLS-1$ } /** * Creates a selection dialog that lists all packages under the given package * fragment root. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected packages (of type * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param root the package fragment root * @param filter the filter * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root, String filter) throws JavaModelException { ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setElements(root.getChildren()); dialog.setFilter(filter); return dialog; } /** * @see createPackageDialog(Shell,IPackageFragmentRoot) */ public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root) throws JavaModelException { return createPackageDialog(parent, root, "A"); //$NON-NLS-1$ } /** * Creates a selection dialog that lists all types in the given scope. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected packages (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param scope the scope that limits which types are included * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_CLASSES</code>, * <code>CONSIDER_INTERFACES</code>, or their bitwise OR * (equivalent to <code>CONSIDER_TYPES</code>) * @param multipleSelection <code>true</code> if multiple selection is allowed * @param filter the filter * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) throws JavaModelException { Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_TYPES) == IJavaElementSearchConstants.CONSIDER_TYPES); if (multipleSelection) { MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, context, scope, style); dialog.setFilter(filter); return dialog; } else { TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, scope, style); dialog.setFilter(filter); return dialog; } } /** * @see createTypeDialog(Shell,IRunnableContext,IJavaSearchScope,int,boolean,String) */ public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) throws JavaModelException { return createTypeDialog(parent, context, scope, style, multipleSelection, "A");//$NON-NLS-1$ } /** * Creates a selection dialog that lists all types in the given scope containing * a standard <code>main</code> method. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected packages (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * <p> * [Issue: IJavaSearchScope is not currently part of the Java core API.] * </p> * <p> * [Issue: SelectionDialogs must be parented. shell must not be null.] * </p> * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param scope the scope that limits which types are included * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, * <code>CONSIDER_EXTERNAL_JARS</code>, or their bitwise OR, or <code>0</code> * @param multipleSelection <code>true</code> if multiple selection is allowed * @param filter the filter * @return a new selection dialog */ public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) { AbstractElementListSelectionDialog dialog= null; if (multipleSelection) { dialog= new MultiMainTypeSelectionDialog(parent, context, scope, style); } else { dialog= new MainTypeSelectionDialog(parent, context, scope, style); } dialog.setFilter(filter); return dialog; } /** * @see createMainTypeDialog(Shell,IRunnableContext,IJavaSearchScope,int,boolean,String) */ public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) { return createMainTypeDialog(parent, context, scope, style, multipleSelection, "A");//$NON-NLS-1$ } /** * Creates a selection dialog that lists all types in the given project. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected packages (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param project the Java project * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_CLASSES</code>, * <code>CONSIDER_INTERFACES</code>, or their bitwise OR * (equivalent to <code>CONSIDER_TYPES</code>) * @param multipleSelection <code>true</code> if multiple selection is allowed * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IProject project, int style, boolean multipleSelection) throws JavaModelException { IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[] { JavaCore.create(project) }); return createTypeDialog(parent, context, scope, style, multipleSelection); } /** * Opens a Java editor on the given Java compilation unit of class file. * If there already is an open Java editor for the given element, it is returned. * <p> * [Issue: Explain semantics of opening an editor on a class file.] * </p> * <p> * [Issue: Explain under which conditions it returns null, throws JavaModelException, * or throws JavaModelException. * ] * </p> * * @param element the input element; either a compilation unit * (<code>ICompilationUnit</code>) or a class file (</code>IClassFile</code>) * @return the editor, or </code>null</code> if wrong element type or opening failed * @exception PartInitException if the editor could not be initialized * @exception JavaModelException if this element does not exist or if an * exception occurs while accessing its underlying resource */ public static IEditorPart openInEditor(IJavaElement element) throws JavaModelException, PartInitException { return EditorUtility.openInEditor(element); } /** * Reveals the source range of the given source reference element in the * given editor. No checking is done if the editor displays a compilation unit or * class file that contains the given source reference. * <p> * [Issue: Explain what is meant by that last sentence.] * </p> * <p> * [Issue: Explain what happens if the source reference is from some other * compilation unit, editor is not open, etc.] * </p> * * @param part the editor displaying the compilation unit or class file * @param element the source reference element defining the source range to be revealed * * @deprecated use <code>revealInEditor(IEditorPart, IJavaElement)</code> instead */ public static void revealInEditor(IEditorPart part, ISourceReference element) { if (element instanceof IJavaElement) revealInEditor(part, (IJavaElement) element); } /** * Reveals the given java element in the given editor. No checking is done if the * editor displays a compilation unit or class file that contains the given element. * If the element is not contained, nothing happens. * @param part the editor displaying a compilation unit or class file * @param element the element to be revealed */ public static void revealInEditor(IEditorPart part, IJavaElement element) { EditorUtility.revealInEditor(part, element); } /** * Returns the working copy manager for the Java UI plug-in. * * @return the working copy manager for the Java UI plug-in */ public static IWorkingCopyManager getWorkingCopyManager() { return JavaPlugin.getDefault().getWorkingCopyManager(); } }
4,381
Bug 4381 Replace from local histroy - workspace element included
- modify a CU in the workspace - select the CU - activate "Replace from local history" - the workspace element is included in the local histroy, but a histroy never includes the actual element. I was really suprised seeing the element.
resolved fixed
5439e11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T19:24:21Z"
"2001-10-11T14:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaAddElementFromHistory.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.util.ResourceBundle; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.*; import org.eclipse.ui.IEditorInput; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.corext.codemanipulation.*; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.compare.*; public class JavaAddElementFromHistory extends JavaHistoryAction { private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.AddFromHistoryAction"; //$NON-NLS-1$ private JavaEditor fEditor; public JavaAddElementFromHistory() { } /** * The optional argument editor is used iff the selection provider's * selection is empty. In this case the editor's CU is the container * to which to add an element from the local history. */ public JavaAddElementFromHistory(JavaEditor editor, ISelectionProvider sp) { super(sp); fEditor= editor; setText(CompareMessages.getString("AddFromHistory.action.label")); //$NON-NLS-1$ update(); } /** * @see Action#run */ public final void run() { String errorTitle= CompareMessages.getString("AddFromHistory.title"); //$NON-NLS-1$ String errorMessage= CompareMessages.getString("AddFromHistory.internalErrorMessage"); //$NON-NLS-1$ Shell shell= JavaPlugin.getActiveWorkbenchShell(); // shell can be null; as a result error dialogs won't be parented ICompilationUnit cu= null; IParent parent= null; IMember input= null; // analyse selection ISelection selection= getSelection(); if (selection.isEmpty()) { // no selection: we try to use the editor's input if (fEditor != null) { IEditorInput editorInput= fEditor.getEditorInput(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); if (manager != null) { cu= manager.getWorkingCopy(editorInput); parent= cu; } } } else { input= getEditionElement(selection); if (input != null) { cu= input.getCompilationUnit(); if (input instanceof IParent) { parent= (IParent)input; input= null; } else { IJavaElement parentElement= input.getParent(); if (parentElement instanceof IParent) parent= (IParent)parentElement; } } else { if (selection instanceof IStructuredSelection) { Object o= ((IStructuredSelection)selection).getFirstElement(); if (o instanceof ICompilationUnit) { cu= (ICompilationUnit) o; parent= cu; } } } } if (parent == null || cu == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } // extract CU from selection if (cu.isWorkingCopy()) cu= (ICompilationUnit) cu.getOriginalElement(); // find underlying file IFile file= null; try { file= (IFile) cu.getUnderlyingResource(); } catch (JavaModelException ex) { JavaPlugin.log(ex); } if (file == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } // get available editions IFileState[] states= null; try { states= file.getHistory(null); } catch (CoreException ex) { JavaPlugin.log(ex); } if (states == null || states.length <= 0) { MessageDialog.openInformation(shell, errorTitle, CompareMessages.getString("AddFromHistory.noHistoryMessage")); //$NON-NLS-1$ return; } // get a TextBuffer where to insert the text TextBuffer buffer= null; try { buffer= TextBuffer.acquire(file); // configure EditionSelectionDialog and let user select an edition ITypedElement target= new JavaTextBufferNode(buffer, cu.getElementName()); ITypedElement[] editions= new ITypedElement[states.length]; for (int i= 0; i < states.length; i++) editions[i]= new HistoryItem(target, states[i]); ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME); EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle); d.setAddMode(true); ITypedElement ti= d.selectEdition(target, editions, parent); if (!(ti instanceof IStreamContentAccessor)) return; // user cancel // from the edition get the lines (text) to insert String[] lines= null; try { lines= JavaCompareUtilities.readLines(((IStreamContentAccessor) ti).getContents()); } catch (CoreException ex) { JavaPlugin.log(ex); } if (lines == null) { MessageDialog.openError(shell, errorTitle, "couldn't get text to insert"); return; } // build the TextEdit that inserts the text into the buffer TextEdit edit= null; if (input != null) edit= new MemberEdit(input, MemberEdit.INSERT_AFTER, lines, CodeFormatterPreferencePage.getTabSize()); else edit= createEdit(lines, parent); if (edit == null) { MessageDialog.openError(shell, errorTitle, "couldn't determine place to insert"); return; } TextBufferEditor editor= new TextBufferEditor(buffer); editor.addTextEdit(edit); editor.performEdits(new NullProgressMonitor()); TextBuffer.commitChanges(buffer, false, new NullProgressMonitor()); } catch(CoreException ex) { JavaPlugin.log(ex); MessageDialog.openError(shell, errorTitle, "error with TextBuffer"); } finally { if (buffer != null) TextBuffer.release(buffer); } } /** * Creates a TextEdit for inserting the given lines into the container. */ private TextEdit createEdit(String[] lines, IParent container) { // find a child where to insert before IJavaElement[] children= null; try { children= container.getChildren(); } catch(JavaModelException ex) { } if (children != null) { IJavaElement candidate= null; for (int i= 0; i < children.length; i++) { IJavaElement chld= children[i]; switch (chld.getElementType()) { case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: // skip these but remember the last of them candidate= chld; continue; default: return new MemberEdit(chld, MemberEdit.INSERT_BEFORE, lines, CodeFormatterPreferencePage.getTabSize()); } } if (candidate != null) return new MemberEdit(candidate, MemberEdit.INSERT_AFTER, lines, CodeFormatterPreferencePage.getTabSize()); } // no children: insert at end (but before closing bracket) if (container instanceof IJavaElement) return new MemberEdit((IJavaElement)container, MemberEdit.ADD_AT_END, lines, CodeFormatterPreferencePage.getTabSize()); return null; } protected boolean isEnabled(ISelection selection) { if (selection.isEmpty()) { if (fEditor != null) { // we check whether editor shows CompilationUnit IEditorInput editorInput= fEditor.getEditorInput(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(editorInput) != null; } return false; } if (selection instanceof IStructuredSelection) { Object o= ((IStructuredSelection)selection).getFirstElement(); if (o instanceof ICompilationUnit) return true; } return getEditionElement(selection) != null; } }
4,381
Bug 4381 Replace from local histroy - workspace element included
- modify a CU in the workspace - select the CU - activate "Replace from local history" - the workspace element is included in the local histroy, but a histroy never includes the actual element. I was really suprised seeing the element.
resolved fixed
5439e11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T19:24:21Z"
"2001-10-11T14:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaCompareUtilities.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.io.*; import java.net.*; import java.util.*; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.core.JavaElement; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.ui.text.JavaTextTools; class JavaCompareUtilities { /** * Returns a name for the given Java element that uses the same conventions * as the JavaNode name of a corresponding element. */ static String getJavaElementID(IJavaElement je) { if (je instanceof IMember && ((IMember)je).isBinary()) return null; StringBuffer sb= new StringBuffer(); switch (je.getElementType()) { case JavaElement.COMPILATION_UNIT: sb.append(JavaElement.JEM_COMPILATIONUNIT); break; case JavaElement.TYPE: sb.append(JavaElement.JEM_TYPE); sb.append(je.getElementName()); break; case JavaElement.FIELD: sb.append(JavaElement.JEM_FIELD); sb.append(je.getElementName()); break; case JavaElement.METHOD: sb.append(JavaElement.JEM_METHOD); sb.append(JavaElementLabels.getElementLabel(je, JavaElementLabels.M_PARAMETER_TYPES)); break; case JavaElement.INITIALIZER: String id= je.getHandleIdentifier(); int pos= id.lastIndexOf(JavaElement.JEM_INITIALIZER); if (pos >= 0) sb.append(id.substring(pos)); break; case JavaElement.PACKAGE_DECLARATION: sb.append(JavaElement.JEM_PACKAGEDECLARATION); break; case JavaElement.IMPORT_CONTAINER: sb.append('<'); break; case JavaElement.IMPORT_DECLARATION: sb.append(JavaElement.JEM_IMPORTDECLARATION); sb.append(je.getElementName()); break; default: return null; } return sb.toString(); } /** * Returns a name which identifies the given typed name. * The type is encoded as a single character at the beginning of the string. */ static String buildID(int type, String name) { StringBuffer sb= new StringBuffer(); switch (type) { case JavaNode.CU: sb.append(JavaElement.JEM_COMPILATIONUNIT); break; case JavaNode.CLASS: case JavaNode.INTERFACE: sb.append(JavaElement.JEM_TYPE); sb.append(name); break; case JavaNode.FIELD: sb.append(JavaElement.JEM_FIELD); sb.append(name); break; case JavaNode.CONSTRUCTOR: case JavaNode.METHOD: sb.append(JavaElement.JEM_METHOD); sb.append(name); break; case JavaNode.INIT: sb.append(JavaElement.JEM_INITIALIZER); sb.append(name); break; case JavaNode.PACKAGE: sb.append(JavaElement.JEM_PACKAGEDECLARATION); break; case JavaNode.IMPORT: sb.append(JavaElement.JEM_IMPORTDECLARATION); sb.append(name); break; case JavaNode.IMPORT_CONTAINER: sb.append('<'); break; default: Assert.isTrue(false); break; } return sb.toString(); } static ImageDescriptor getImageDescriptor(String relativePath) { JavaPlugin plugin= JavaPlugin.getDefault(); URL installURL= null; if (plugin != null) installURL= plugin.getDescriptor().getInstallURL(); if (installURL != null) { try { URL url= new URL(installURL, "icons/full/" + relativePath); //$NON-NLS-1$ return ImageDescriptor.createFromURL(url); } catch (MalformedURLException e) { Assert.isTrue(false); } } return null; } static JavaTextTools getJavaTextTools() { JavaPlugin plugin= JavaPlugin.getDefault(); if (plugin != null) return plugin.getJavaTextTools(); return null; } static IDocumentPartitioner createJavaPartitioner() { JavaTextTools tools= getJavaTextTools(); if (tools != null) return tools.createDocumentPartitioner(); return null; } /** * Returns null if an error occurred. */ static String readString(InputStream is) { if (is == null) return null; BufferedReader reader= null; try { StringBuffer buffer= new StringBuffer(); char[] part= new char[2048]; int read= 0; reader= new BufferedReader(new InputStreamReader(is)); while ((read= reader.read(part)) != -1) buffer.append(part, 0, read); return buffer.toString(); } catch (IOException ex) { } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { JavaPlugin.log(ex); } } } return null; } /** * Breaks the given string into lines and strips off the line terminator. */ static String[] readLines(InputStream is) { String[] lines= null; try { StringBuffer sb= null; List list= new ArrayList(); while (true) { int c= is.read(); if (c == -1) break; if (c == '\n' || c == '\r') { if (sb != null) list.add(sb.toString()); sb= null; } else { if (sb == null) sb= new StringBuffer(); sb.append((char)c); } } if (sb != null) list.add(sb.toString()); return (String[]) list.toArray(new String[list.size()]); } catch (IOException ex) { return null; } finally { if (is != null) { try { is.close(); } catch (IOException ex) { } } } } }
4,381
Bug 4381 Replace from local histroy - workspace element included
- modify a CU in the workspace - select the CU - activate "Replace from local history" - the workspace element is included in the local histroy, but a histroy never includes the actual element. I was really suprised seeing the element.
resolved fixed
5439e11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T19:24:21Z"
"2001-10-11T14:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaCompareWithEditionAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.util.ResourceBundle; import org.eclipse.swt.widgets.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.viewers.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.corext.codemanipulation.*; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.compare.*; import org.eclipse.compare.internal.Utilities; /** * Provides "Replace from local history" for Java elements. */ public class JavaCompareWithEditionAction extends JavaHistoryAction { static class CompareWithEditionDialog extends EditionSelectionDialog { ResourceBundle fBundle; CompareWithEditionDialog(Shell parent, ResourceBundle bundle) { super(parent, bundle); fBundle= bundle; } protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, Utilities.getString(fBundle, "closeButton.label"), false); //$NON-NLS-1$ } /** * Overidden to disable dismiss on double click (see PR 1GI3KUR). */ protected void okPressed() { } } private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.CompareWithEditionAction"; //$NON-NLS-1$ public JavaCompareWithEditionAction() { } public JavaCompareWithEditionAction(ISelectionProvider sp) { super(sp); setText(CompareMessages.getString("ReplaceFromHistory.action.label")); //$NON-NLS-1$ update(); } /** * @see Action#run */ public final void run() { String errorTitle= CompareMessages.getString("ReplaceFromHistory.title"); //$NON-NLS-1$ String errorMessage= CompareMessages.getString("ReplaceFromHistory.internalErrorMessage"); //$NON-NLS-1$ Shell shell= JavaPlugin.getActiveWorkbenchShell(); // shell can be null; as a result error dialogs won't be parented ISelection selection= getSelection(); IMember input= getEditionElement(selection); if (input == null) { // shouldn't happen because Action should not be enabled in the first place MessageDialog.openInformation(shell, errorTitle, errorMessage); return; } // extract CU from selection ICompilationUnit cu= input.getCompilationUnit(); if (cu.isWorkingCopy()) cu= (ICompilationUnit) cu.getOriginalElement(); // find underlying file IFile file= null; try { file= (IFile) cu.getUnderlyingResource(); } catch (JavaModelException ex) { JavaPlugin.log(ex); } if (file == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } // setup array of editions int numberOfEditions= 1; IFileState[] states= null; // add available editions try { states= file.getHistory(null); } catch (CoreException ex) { JavaPlugin.log(ex); } if (states != null) numberOfEditions += states.length; ITypedElement[] editions= new ITypedElement[numberOfEditions]; editions[0]= new ResourceNode(file); if (states != null) for (int i= 0; i < states.length; i++) editions[i+1]= new HistoryItem(editions[0], states[i]); // get a TextBuffer where to insert the text TextBuffer buffer= null; try { buffer= TextBuffer.acquire(file); ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME); EditionSelectionDialog d= new CompareWithEditionDialog(shell, bundle); ITypedElement ti= d.selectEdition(new JavaTextBufferNode(buffer, cu.getElementName()), editions, input); if (ti instanceof IStreamContentAccessor) { IStreamContentAccessor sca= (IStreamContentAccessor) ti; // from the edition get the lines (text) to insert String[] lines= null; try { lines= JavaCompareUtilities.readLines(((IStreamContentAccessor) ti).getContents()); } catch (CoreException ex) { JavaPlugin.log(ex); } if (lines == null) { MessageDialog.openError(shell, errorTitle, "couldn't get text to insert"); return; } TextEdit edit= new MemberEdit(input, MemberEdit.REPLACE, lines, CodeFormatterPreferencePage.getTabSize()); TextBufferEditor editor= new TextBufferEditor(buffer); editor.addTextEdit(edit); editor.performEdits(new NullProgressMonitor()); TextBuffer.commitChanges(buffer, false, new NullProgressMonitor()); } } catch(CoreException ex) { JavaPlugin.log(ex); MessageDialog.openError(shell, errorTitle, "error with TextBuffer"); } finally { if (buffer != null) TextBuffer.release(buffer); } } protected boolean isEnabled(ISelection selection) { return getEditionElement(selection) != null; } }
4,381
Bug 4381 Replace from local histroy - workspace element included
- modify a CU in the workspace - select the CU - activate "Replace from local history" - the workspace element is included in the local histroy, but a histroy never includes the actual element. I was really suprised seeing the element.
resolved fixed
5439e11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T19:24:21Z"
"2001-10-11T14:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaReplaceWithEditionAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.util.ResourceBundle; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.corext.codemanipulation.*; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.compare.*; /** * Provides "Replace from local history" for Java elements. */ public class JavaReplaceWithEditionAction extends JavaHistoryAction { private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.ReplaceWithEditionAction"; //$NON-NLS-1$ public JavaReplaceWithEditionAction() { } public JavaReplaceWithEditionAction(ISelectionProvider sp) { super(sp); setText(CompareMessages.getString("ReplaceFromHistory.action.label")); //$NON-NLS-1$ update(); } /** * @see Action#run */ public final void run() { String errorTitle= CompareMessages.getString("ReplaceFromHistory.title"); //$NON-NLS-1$ String errorMessage= CompareMessages.getString("ReplaceFromHistory.internalErrorMessage"); //$NON-NLS-1$ Shell shell= JavaPlugin.getActiveWorkbenchShell(); // shell can be null; as a result error dialogs won't be parented ISelection selection= getSelection(); IMember input= getEditionElement(selection); if (input == null) { // shouldn't happen because Action should not be enabled in the first place MessageDialog.openInformation(shell, errorTitle, errorMessage); return; } // extract CU from selection ICompilationUnit cu= input.getCompilationUnit(); if (cu.isWorkingCopy()) cu= (ICompilationUnit) cu.getOriginalElement(); // find underlying file IFile file= null; try { file= (IFile) cu.getUnderlyingResource(); } catch (JavaModelException ex) { JavaPlugin.log(ex); } if (file == null) { MessageDialog.openError(shell, errorTitle, errorMessage); return; } // setup array of editions int numberOfEditions= 1; IFileState[] states= null; // add available editions try { states= file.getHistory(null); } catch (CoreException ex) { JavaPlugin.log(ex); } if (states != null) numberOfEditions += states.length; ITypedElement[] editions= new ITypedElement[numberOfEditions]; editions[0]= new ResourceNode(file); if (states != null) for (int i= 0; i < states.length; i++) editions[i+1]= new HistoryItem(editions[0], states[i]); // get a TextBuffer where to insert the text TextBuffer buffer= null; try { buffer= TextBuffer.acquire(file); ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME); EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle); ITypedElement ti= d.selectEdition(new JavaTextBufferNode(buffer, cu.getElementName()), editions, input); if (ti instanceof IStreamContentAccessor) { IStreamContentAccessor sca= (IStreamContentAccessor) ti; // from the edition get the lines (text) to insert String[] lines= null; try { lines= JavaCompareUtilities.readLines(((IStreamContentAccessor) ti).getContents()); } catch (CoreException ex) { JavaPlugin.log(ex); } if (lines == null) { MessageDialog.openError(shell, errorTitle, "couldn't get text to insert"); return; } TextEdit edit= new MemberEdit(input, MemberEdit.REPLACE, lines, CodeFormatterPreferencePage.getTabSize()); TextBufferEditor editor= new TextBufferEditor(buffer); editor.addTextEdit(edit); editor.performEdits(new NullProgressMonitor()); TextBuffer.commitChanges(buffer, false, new NullProgressMonitor()); } } catch(CoreException ex) { JavaPlugin.log(ex); MessageDialog.openError(shell, errorTitle, "error with TextBuffer"); } finally { if (buffer != null) TextBuffer.release(buffer); } } protected boolean isEnabled(ISelection selection) { return getEditionElement(selection) != null; } }
4,381
Bug 4381 Replace from local histroy - workspace element included
- modify a CU in the workspace - select the CU - activate "Replace from local history" - the workspace element is included in the local histroy, but a histroy never includes the actual element. I was really suprised seeing the element.
resolved fixed
5439e11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T19:24:21Z"
"2001-10-11T14:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaTextBufferNode.java
4,381
Bug 4381 Replace from local histroy - workspace element included
- modify a CU in the workspace - select the CU - activate "Replace from local history" - the workspace element is included in the local histroy, but a histroy never includes the actual element. I was really suprised seeing the element.
resolved fixed
5439e11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-29T19:24:21Z"
"2001-10-11T14:20:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/TextBufferNode.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.io.*; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.internal.corext.codemanipulation.TextBuffer; import org.eclipse.compare.*; /** * Implements the IStreamContentAccessor and ITypedElement protocols * for a TextBuffer. */ class JavaTextBufferNode implements ITypedElement, IStreamContentAccessor { private TextBuffer fBuffer; private String fName; JavaTextBufferNode(TextBuffer buffer, String name) { fBuffer= buffer; } public String getName() { return fName; } public String getType() { return "java"; } public Image getImage() { return null; } public InputStream getContents() { return new ByteArrayInputStream(fBuffer.getContent().getBytes()); } }
4,974
Bug 4974 Set classpath / output location should be one operation
204: 1. create a project with 'src' as source folder and 'bin' as output location. 2. in the project properties change the setting to use the project as source folder and the project as output location. Press Ok You get the error message: 'Cannot nest outputfolder /xy in source folder /xy/src' The problem is that setting outputlocation and classpath are two operations. By setting the first, an illegal state is created. -> Like the validation (checking classpath and outputlocation at once), the setting of classpath / output location should be offered as one operation. Note that the error message is strange. I guess it should say: '/xy/src' can not be nested in '/xy'
resolved fixed
35d95cb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-11-30T15:01:58Z"
"2001-10-15T10:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; import org.eclipse.jdt.internal.ui.wizards.swt.MGridData; import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout; public class BuildPathsBlock { private IWorkspaceRoot fWorkspaceRoot; private CheckedListDialogField fClassPathList; private StringDialogField fBuildPathDialogField; private StatusInfo fClassPathStatus; private StatusInfo fBuildPathStatus; private IJavaProject fCurrJProject; private IPath fOutputLocationPath; private IStatusChangeListener fContext; private Control fSWTWidget; private boolean fIsNewProject; private SourceContainerWorkbookPage fSourceContainerPage; private ProjectsWorkbookPage fProjectsPage; private LibrariesWorkbookPage fLibrariesPage; private BuildPathBasePage fCurrPage; public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean isNewProject) { fWorkspaceRoot= root; fContext= context; fIsNewProject= isNewProject; fSourceContainerPage= null; fLibrariesPage= null; fProjectsPage= null; fCurrPage= null; BuildPathAdapter adapter= new BuildPathAdapter(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$ }; fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fClassPathList.setDialogFieldListener(adapter); fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); fClassPathList.setUpButtonIndex(0); fClassPathList.setDownButtonIndex(1); fClassPathList.setCheckAllButtonIndex(3); fClassPathList.setUncheckAllButtonIndex(4); if (isNewProject) { fBuildPathDialogField= new StringDialogField(); } else { StringButtonDialogField dialogField= new StringButtonDialogField(adapter); dialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$ fBuildPathDialogField= dialogField; } fBuildPathDialogField.setDialogFieldListener(adapter); fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$ fBuildPathStatus= new StatusInfo(); fClassPathStatus= new StatusInfo(); fCurrJProject= null; } // -------- UI creation --------- public Control createControl(Composite parent) { fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); MGridLayout layout= new MGridLayout(); layout.marginWidth= 0; layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, parent); layout.minimumHeight= SWTUtil.convertHeightInCharsToPixels(20, parent); layout.numColumns= 1; composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new MGridData(MGridData.FILL_BOTH)); folder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabChanged(e.item); } }); ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry(); TabItem item; fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField, fIsNewProject); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT)); item.setData(fSourceContainerPage); item.setControl(fSourceContainerPage.getControl(folder)); IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); fProjectsPage= new ProjectsWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$ item.setImage(projectImage); item.setData(fProjectsPage); item.setControl(fProjectsPage.getControl(folder)); fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY)); item.setData(fLibrariesPage); item.setControl(fLibrariesPage.getControl(folder)); // a non shared image Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage(); composite.addDisposeListener(new ImageDisposer(cpoImage)); ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$ item.setImage(cpoImage); item.setData(ordpage); item.setControl(ordpage.getControl(folder)); if (fCurrJProject != null) { fSourceContainerPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); } Composite editorcomp= new Composite(composite, SWT.NONE); DialogField[] editors= new DialogField[] { fBuildPathDialogField }; LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0, 0, 0); int maxFieldWidth= SWTUtil.convertWidthInCharsToPixels(40, parent); LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth); editorcomp.setLayoutData(new MGridData(MGridData.FILL_HORIZONTAL)); if (fIsNewProject) { folder.setSelection(0); fCurrPage= fSourceContainerPage; } else { folder.setSelection(3); fCurrPage= ordpage; fClassPathList.selectFirstElement(); } WorkbenchHelp.setHelp(composite, new Object[] { IJavaHelpContextIds.BUILD_PATH_BLOCK }); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Initializes the classpath for the given project. Multiple calls to init are allowed, * but all existing settings will be cleared and replace by the given or default paths. * @param project The java project to configure. Does not have to exist. * @param outputLocation The output location to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * output location of the existing project * @param classpathEntries The classpath entries to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * classpath entries of the existing project */ public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) { fCurrJProject= jproject; boolean projExists= false; try { IProject project= fCurrJProject.getProject(); projExists= (project.exists() && project.hasNature(JavaCore.NATURE_ID)); if (projExists) { if (outputLocation == null) { outputLocation= fCurrJProject.getOutputLocation(); } if (classpathEntries == null) { classpathEntries= fCurrJProject.getRawClasspath(); } } } catch (CoreException e) { JavaPlugin.log(e.getStatus()); } if (outputLocation == null) { outputLocation= getDefaultBuildPath(jproject); } List newClassPath; if (classpathEntries == null) { newClassPath= getDefaultClassPath(jproject); } else { newClassPath= new ArrayList(); for (int i= 0; i < classpathEntries.length; i++) { IClasspathEntry curr= classpathEntries[i]; int entryKind= curr.getEntryKind(); IPath path= curr.getPath(); boolean isExported= curr.isExported(); // get the resource IResource res= null; boolean isMissing= false; if (entryKind != IClasspathEntry.CPE_VARIABLE) { res= fWorkspaceRoot.findMember(path); if (res == null) { isMissing= (entryKind != IClasspathEntry.CPE_LIBRARY || !path.toFile().isFile()); } } else { IPath resolvedPath= JavaCore.getResolvedVariablePath(path); isMissing= (resolvedPath == null) || !resolvedPath.toFile().isFile(); } CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported); if (projExists) { elem.setIsMissing(isMissing); } newClassPath.add(elem); } } List exportedEntries = new ArrayList(); for (int i= 0; i < newClassPath.size(); i++) { CPListElement curr= (CPListElement) newClassPath.get(i); if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { exportedEntries.add(curr); } } // inits the dialog field fBuildPathDialogField.setText(outputLocation.makeRelative().toString()); fClassPathList.setElements(newClassPath); fClassPathList.setCheckedElements(exportedEntries); if (fSourceContainerPage != null) { fSourceContainerPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); } doStatusLineUpdate(); } // -------- public api -------- /** * Returns the Java project. Can return <code>null<code> if the page has not * been initialized. */ public IJavaProject getJavaProject() { return fCurrJProject; } /** * Returns the current output location. Note that the path returned must not be valid. */ public IPath getOutputLocation() { return new Path(fBuildPathDialogField.getText()).makeAbsolute(); } /** * Returns the current class path (raw). Note that the entries returned must not be valid. */ public IClasspathEntry[] getRawClassPath() { List elements= fClassPathList.getElements(); int nElements= elements.size(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= 0; i < nElements; i++) { CPListElement currElement= (CPListElement) elements.get(i); entries[i]= currElement.getClasspathEntry(); } return entries; } // -------- evaluate default settings -------- private List getDefaultClassPath(IJavaProject jproj) { List list= new ArrayList(); IResource srcFolder; if (JavaBasePreferencePage.useSrcAndBinFolders()) { srcFolder= jproj.getProject().getFolder("src"); //$NON-NLS-1$ } else { srcFolder= jproj.getProject(); } list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder)); IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE); IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE); IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE); CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false); list.add(elem); return list; } private IPath getDefaultBuildPath(IJavaProject jproj) { if (JavaBasePreferencePage.useSrcAndBinFolders()) { return jproj.getProject().getFullPath().append("bin"); //$NON-NLS-1$ } else { return jproj.getProject().getFullPath(); } } private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { buildPathChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { buildPathDialogFieldChanged(field); } } private void buildPathChangeControlPressed(DialogField field) { if (field == fBuildPathDialogField) { IContainer container= chooseContainer(); if (container != null) { fBuildPathDialogField.setText(container.getFullPath().toString()); } } } private void buildPathDialogFieldChanged(DialogField field) { if (field == fClassPathList) { updateClassPathStatus(); updateBuildPathStatus(); } else if (field == fBuildPathDialogField) { updateBuildPathStatus(); } doStatusLineUpdate(); } // -------- verification ------------------------------- private void doStatusLineUpdate() { IStatus res= findMostSevereStatus(); fContext.statusChanged(res); } private IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus); } /** * Validates the build path. */ private void updateClassPathStatus() { fClassPathStatus.setOK(); List elements= fClassPathList.getElements(); boolean entryMissing= false; IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); boolean isChecked= fClassPathList.isChecked(currElement); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!isChecked) { fClassPathList.setCheckedWithoutUpdate(currElement, true); } } else { currElement.setExported(isChecked); } entries[i]= currElement.getClasspathEntry(); entryMissing= entryMissing || currElement.isMissing(); } if (entryMissing) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$ } if (fCurrJProject.hasClasspathCycle(entries)) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$ } } /** * Validates output location & build path. */ private void updateBuildPathStatus() { fOutputLocationPath= null; String text= fBuildPathDialogField.getText(); if ("".equals(text)) { //$NON-NLS-1$ fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$ return; } IPath path= getOutputLocation(); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { // if exists, must be a folder or project if (res.getType() == IResource.FILE) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$ return; } } else { // allows the build path to be in a different project, but must exists and be open IPath projPath= path.uptoSegment(1); if (!projPath.equals(fCurrJProject.getProject().getFullPath())) { IProject proj= (IProject)fWorkspaceRoot.findMember(projPath); if (proj == null || !proj.isOpen()) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.BuildPathProjNotExists")); //$NON-NLS-1$ return; } } } fOutputLocationPath= path; List elements= fClassPathList.getElements(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); entries[i]= currElement.getClasspathEntry(); } IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path); if (!status.isOK()) { fBuildPathStatus.setError(status.getMessage()); return; } fBuildPathStatus.setOK(); } // -------- creation ------------------------------- /** * Creates a runnable that sets the configured build paths. */ public IRunnableWithProgress getRunnable() { final List classPathEntries= fClassPathList.getElements(); final IPath path= getOutputLocation(); return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 12); //$NON-NLS-1$ try { createJavaProject(classPathEntries, path, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; } /** * Creates the Java project and sets the configured build path and output location. * If the project already exists only build paths are updated. */ private void createJavaProject(List classPathEntries, IPath buildPath, IProgressMonitor monitor) throws CoreException { IProject project= fCurrJProject.getProject(); if (!project.exists()) { project.create(null); } if (!project.isOpen()) { project.open(null); } // create java nature if (!project.hasNature(JavaCore.NATURE_ID)) { addNatureToProject(project, JavaCore.NATURE_ID, null); } monitor.worked(1); String[] prevRequiredProjects= fCurrJProject.getRequiredProjectNames(); // create and set the output path first if (!fWorkspaceRoot.exists(buildPath)) { IFolder folder= fWorkspaceRoot.getFolder(buildPath); CoreUtility.createFolder(folder, true, true, null); } monitor.worked(1); fCurrJProject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 3)); int nEntries= classPathEntries.size(); IClasspathEntry[] classpath= new IClasspathEntry[nEntries]; // create and set the class path for (int i= 0; i < nEntries; i++) { CPListElement entry= ((CPListElement)classPathEntries.get(i)); IResource res= entry.getResource(); if ((res instanceof IFolder) && !res.exists()) { CoreUtility.createFolder((IFolder)res, true, true, null); } classpath[i]= entry.getClasspathEntry(); } monitor.worked(1); fCurrJProject.setRawClasspath(classpath, new SubProgressMonitor(monitor, 5)); } /** * Adds a nature to a project */ private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException { IProjectDescription description = proj.getDescription(); String[] prevNatures= description.getNatureIds(); String[] newNatures= new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length]= natureId; description.setNatureIds(newNatures); proj.setDescription(description, monitor); } // ---------- util method ------------ private IContainer chooseContainer() { Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class }; ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); IProject[] allProjects= fWorkspaceRoot.getProjects(); ArrayList rejectedElements= new ArrayList(allProjects.length); IProject currProject= fCurrJProject.getProject(); for (int i= 0; i < allProjects.length; i++) { if (!allProjects[i].equals(currProject)) { rejectedElements.add(allProjects[i]); } } ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSelection= null; if (fOutputLocationPath != null) { initSelection= fWorkspaceRoot.findMember(fOutputLocationPath); } ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$ dialog.setValidator(validator); dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSelection); if (dialog.open() == dialog.OK) { return (IContainer)dialog.getFirstResult(); } return null; } // -------- tab switching ---------- private void tabChanged(Widget widget) { if (widget instanceof TabItem) { BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData(); if (fCurrPage != null) { List selection= fCurrPage.getSelection(); if (!selection.isEmpty()) { newPage.setSelection(selection); } } fCurrPage= newPage; } } }
6,536
Bug 6536 Add Javadoc on field in TH does nothing
1. Select a field in the Type Hierarchy view 2. From its context menu select "Add Javadoc" ==> nothing happens. Either this menu should be removed or (preferably) the action should add the fields Javadoc.
verified fixed
49752b4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-04T10:43:34Z"
"2001-12-04T10:00:00Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddJavaDocStubAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.actions; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.corext.codegeneration.AddJavaDocStubOperation; import org.eclipse.jdt.internal.corext.codegeneration.CodeGenerationSettings; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; /** * Create Java Doc Stubs for selected members * Always forces the he field to be in an open editor. The result is unsaved, * so the user can decide if he wnats to accept the changes */ public class AddJavaDocStubAction extends Action { private ISelectionProvider fSelectionProvider; public AddJavaDocStubAction(ISelectionProvider selProvider) { super(JavaUIMessages.getString("AddJavaDocStubAction.label")); //$NON-NLS-1$ setDescription(JavaUIMessages.getString("AddJavaDocStubAction.description")); //$NON-NLS-1$ setToolTipText(JavaUIMessages.getString("AddJavaDocStubAction.tooltip")); //$NON-NLS-1$ fSelectionProvider= selProvider; } public void run() { IMember[] members= getSelectedMembers(); if (members == null || members.length == 0) { return; } try { ICompilationUnit cu= members[0].getCompilationUnit(); // open the editor, forces the creation of a working copy IEditorPart editor= EditorUtility.openInEditor(cu); ICompilationUnit workingCopyCU; IMember[] workingCopyMembers; if (cu.isWorkingCopy()) { workingCopyCU= cu; workingCopyMembers= members; } else { // get the corresponding elements from the working copy workingCopyCU= EditorUtility.getWorkingCopy(cu); if (workingCopyCU == null) { showError(JavaUIMessages.getString("AddJavaDocStubsAction.error.noWorkingCopy")); //$NON-NLS-1$ return; } workingCopyMembers= new IMember[members.length]; for (int i= 0; i < members.length; i++) { IMember member= members[i]; IMember workingCopyMember= (IMember) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, member); if (workingCopyMember == null) { showError(JavaUIMessages.getFormattedString("AddJavaDocStubsAction.error.memberNotExisting", member.getElementName())); //$NON-NLS-1$ return; } workingCopyMembers[i]= workingCopyMember; } } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); AddJavaDocStubOperation op= new AddJavaDocStubOperation(workingCopyMembers, settings); ProgressMonitorDialog dialog= new ProgressMonitorDialog(JavaPlugin.getActiveWorkbenchShell()); dialog.run(false, true, new WorkbenchRunnableWrapper(op)); EditorUtility.revealInEditor(editor, members[0]); } catch (InvocationTargetException e) { JavaPlugin.log(e); showError(JavaUIMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$ } catch (InterruptedException e) { // operation cancelled } catch (CoreException e) { JavaPlugin.log(e.getStatus()); showError(JavaUIMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$ return; } } private void showError(String message) { Shell shell= JavaPlugin.getActiveWorkbenchShell(); String title= JavaUIMessages.getString("AddJavaDocStubsAction.error.dialogTitle"); //$NON-NLS-1$ MessageDialog.openError(shell, title, message); } private IMember[] getSelectedMembers() { ISelection sel= fSelectionProvider.getSelection(); if (sel instanceof IStructuredSelection) { List elements= ((IStructuredSelection)sel).toList(); int nElements= elements.size(); if (nElements > 0) { IMember[] res= new IMember[nElements]; ICompilationUnit cu= null; for (int i= 0; i < nElements; i++) { Object curr= elements.get(i); if (curr instanceof IMember) { IMember member= (IMember)curr; if (i == 0) { cu= member.getCompilationUnit(); if (cu == null) { return null; } } else if (!cu.equals(member.getCompilationUnit())) { return null; } res[i]= member; } else { return null; } } return res; } } return null; } public boolean canActionBeAdded() { return getSelectedMembers() != null; } }
6,525
Bug 6525 wrong indent when using replace from local history
JUnit set-up 1) Change junit.tests.createResult() 2) save 3) replace from local history 4) select previous edition -> method is inserted with wrong indent repeat 3) indent is accumulated
verified fixed
4b07fd1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-04T16:56:37Z"
"2001-12-03T22:53:20Z"
org.eclipse.jdt.ui/core
6,525
Bug 6525 wrong indent when using replace from local history
JUnit set-up 1) Change junit.tests.createResult() 2) save 3) replace from local history 4) select previous edition -> method is inserted with wrong indent repeat 3) indent is accumulated
verified fixed
4b07fd1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-04T16:56:37Z"
"2001-12-03T22:53:20Z"
extension/org/eclipse/jdt/internal/corext/codemanipulation/MemberEdit.java
6,407
Bug 6407 reminder: register the context menu in the JavaOutlinePage
the context menu in the JavaOutlinePage should be registered with the page's site.
resolved fixed
31519fa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-04T17:24:24Z"
"2001-11-28T23:26:40Z"
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup; import org.eclipse.jdt.internal.ui.actions.GenerateGroup; import org.eclipse.jdt.internal.ui.actions.OpenHierarchyPerspectiveItem; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup; import org.eclipse.jdt.internal.ui.reorg.DeleteAction; import org.eclipse.jdt.internal.ui.reorg.ReorgGroup; import org.eclipse.jdt.internal.ui.search.JavaSearchGroup; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementSorter; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * The content outline page of the Java editor. The viewer implements a proprietary * update mechanism based on Java model deltas. It does not react on domain changes. * It is specified to show the content of ICompilationUnits and IClassFiles. */ class JavaOutlinePage extends Page implements IContentOutlinePage { /** * The element change listener of the java outline viewer. * @see IElementChangedListener */ class ElementChangedListener implements IElementChangedListener { public void elementChanged(final ElementChangedEvent e) { Display d= getControl().getDisplay(); if (d != null) { d.asyncExec(new Runnable() { public void run() { IJavaElementDelta delta= findElement( (ICompilationUnit) fInput, e.getDelta()); if (delta != null && fOutlineViewer != null) { fOutlineViewer.reconcile(delta); } } }); } } protected IJavaElementDelta findElement(ICompilationUnit unit, IJavaElementDelta delta) { if (delta == null || unit == null) return null; IJavaElement element= delta.getElement(); if (unit.equals(element)) return delta; if (element.getElementType() > IJavaElement.CLASS_FILE) return null; IJavaElementDelta[] children= delta.getAffectedChildren(); if (children == null || children.length == 0) return null; for (int i= 0; i < children.length; i++) { IJavaElementDelta d= findElement(unit, children[i]); if (d != null) return d; } return null; } }; /** * Content provider for the children of an ICompilationUnit or * an IClassFile * @see ITreeContentProvider */ class ChildrenProvider implements ITreeContentProvider { private ElementChangedListener fListener; private JavaOutlineErrorTickUpdater fErrorTickUpdater; protected boolean matches(IJavaElement element) { if (element.getElementType() == IJavaElement.METHOD) { String name= element.getElementName(); return (name != null && name.indexOf('<') >= 0); } return false; } protected IJavaElement[] filter(IJavaElement[] children) { boolean initializers= false; for (int i= 0; i < children.length; i++) { if (matches(children[i])) { initializers= true; break; } } if (!initializers) return children; Vector v= new Vector(); for (int i= 0; i < children.length; i++) { if (matches(children[i])) continue; v.addElement(children[i]); } IJavaElement[] result= new IJavaElement[v.size()]; v.copyInto(result); return result; } public Object[] getChildren(Object parent) { if (parent instanceof IParent) { IParent c= (IParent) parent; try { return filter(c.getChildren()); } catch (JavaModelException x) { JavaPlugin.getDefault().logErrorStatus(JavaEditorMessages.getString("JavaOutlinePage.error.ChildrenProvider.getChildren.message1"), x.getStatus()); //$NON-NLS-1$ } } return new Object[0]; } public Object[] getElements(Object parent) { return getChildren(parent); } public Object getParent(Object child) { if (child instanceof IJavaElement) { IJavaElement e= (IJavaElement) child; return e.getParent(); } return null; } public boolean hasChildren(Object parent) { if (parent instanceof IParent) { IParent c= (IParent) parent; try { IJavaElement[] children= filter(c.getChildren()); return (children != null && children.length > 0); } catch (JavaModelException x) { JavaPlugin.getDefault().logErrorStatus(JavaEditorMessages.getString("JavaOutlinePage.error.ChildrenProvider.hasChildren.message1"), x.getStatus()); //$NON-NLS-1$ } } return false; } public boolean isDeleted(Object o) { return false; } public void dispose() { if (fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; } if (fErrorTickUpdater != null) { fErrorTickUpdater.setAnnotationModel(null); fErrorTickUpdater= null; } } /** * @see IContentProvider#inputChanged(Viewer, Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { boolean isCU= (newInput instanceof ICompilationUnit); if (isCU && fListener == null) { fListener= new ElementChangedListener(); JavaCore.addElementChangedListener(fListener); fErrorTickUpdater= new JavaOutlineErrorTickUpdater(fOutlineViewer); fErrorTickUpdater.setAnnotationModel(fEditor.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput())); } else if (isCU && fErrorTickUpdater != null) { fErrorTickUpdater.setAnnotationModel(fEditor.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput())); } else if (!isCU && fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; fErrorTickUpdater.setAnnotationModel(null); fErrorTickUpdater= null; } } }; class JavaOutlineViewer extends TreeViewer { /** * Indicates an item which has been reused. At the point of * its reuse it has been expanded. This field is used to * communicate between <code>internalExpandToLevel</code> and * <code>reuseTreeItem</code>. */ private Item fReusedExpandedItem; public JavaOutlineViewer(Tree tree) { super(tree); setAutoExpandLevel(ALL_LEVELS); } /** * Investigates the given element change event and if affected incrementally * updates the outline. */ public void reconcile(IJavaElementDelta delta) { if (getSorter() == null) { Widget w= findItem(fInput); if (w != null) update(w, delta); } else { // just for now refresh(); } } /** * @see TreeViewer#internalExpandToLevel */ protected void internalExpandToLevel(Widget node, int level) { if (node instanceof Item) { Item i= (Item) node; if (i.getData() instanceof IJavaElement) { IJavaElement je= (IJavaElement) i.getData(); if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) { if (i != fReusedExpandedItem) { setExpanded(i, false); return; } } } } super.internalExpandToLevel(node, level); } protected void reuseTreeItem(Item item, Object element) { // remove children Item[] c= getChildren(item); if (c != null && c.length > 0) { if (getExpanded(item)) fReusedExpandedItem= item; for (int k= 0; k < c.length; k++) { if (c[k].getData() != null) disassociate(c[k]); c[k].dispose(); } } updateItem(item, element); updatePlus(item, element); internalExpandToLevel(item, ALL_LEVELS); fReusedExpandedItem= null; } /** * @see TreeViewer#createTreeItem */ protected void createTreeItem(Widget parent, Object element, int ix) { Item[] children= getChildren(parent); boolean expand= (parent instanceof Item && (children == null || children.length == 0)); Item item= newItem(parent, SWT.NULL, ix); updateItem(item, element); updatePlus(item, element); if (expand) setExpanded((Item) parent, true); internalExpandToLevel(item, ALL_LEVELS); } protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) { if (element instanceof IMethod) { if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { try { return JavaModelUtil.isMainMethod((IMethod)element); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } return "main".equals(element.getElementName()); //$NON-NLS-1$ } return false; } protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException { if (element instanceof IMember) return ((IMember) element).getNameRange(); if (element instanceof ISourceReference) return ((ISourceReference) element).getSourceRange(); return null; } protected boolean overlaps(ISourceRange range, int start, int end) { return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end; } protected boolean filtered(IJavaElement parent, IJavaElement child) { Object[] result= new Object[] { child }; ViewerFilter[] filters= getFilters(); for (int i= 0; i < filters.length; i++) { result= filters[i].filter(this, parent, result); if (result.length == 0) return true; } return false; } protected void update(Widget w, IJavaElementDelta delta) { Item item; Object element; IJavaElement parent= delta.getElement(); IJavaElementDelta[] affected= delta.getAffectedChildren(); Item[] children= getChildren(w); boolean doUpdateParent= false; Vector deletions= new Vector(); Vector additions= new Vector(); go1: for (int i= 0; i < children.length; i++) { item= children[i]; element= item.getData(); for (int j= 0; j < affected.length; j++) { IJavaElement affectedElement= affected[j].getElement(); int status= affected[j].getKind(); if (affectedElement.equals(element)) { // removed if ((status & IJavaElementDelta.REMOVED) != 0) { deletions.addElement(item); doUpdateParent= doUpdateParent || mustUpdateParent(affected[j], affectedElement); continue go1; } // changed if ((status & IJavaElementDelta.CHANGED) != 0) { int change= affected[j].getFlags(); doUpdateParent= doUpdateParent || mustUpdateParent(affected[j], affectedElement); if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { if (filtered(parent, affectedElement)) deletions.addElement(item); else updateItem(item, affectedElement); } if ((change & IJavaElementDelta.F_CONTENT) != 0) updateItem(item, affectedElement); if ((change & IJavaElementDelta.F_CHILDREN) != 0) update(item, affected[j]); continue go1; } } else { // changed if ((status & IJavaElementDelta.CHANGED) != 0 && (affected[j].getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 && !filtered(parent, affectedElement)) additions.addElement(affected[j]); } } } // find all elements to add IJavaElementDelta[] add= delta.getAddedChildren(); if (additions.size() > 0) { IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()]; System.arraycopy(add, 0, tmp, 0, add.length); for (int i= 0; i < additions.size(); i++) tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i); add= tmp; } // add at the right position go2: for (int i= 0; i < add.length; i++) { try { IJavaElement e= add[i].getElement(); if (filtered(parent, e)) continue go2; doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e); ISourceRange rng= getSourceRange(e); int start= rng.getOffset(); int end= start + rng.getLength() - 1; Item last= null; item= null; children= getChildren(w); for (int j= 0; j < children.length; j++) { item= children[j]; IJavaElement r= (IJavaElement) item.getData(); if (r == null) { // parent node collapsed and not be opened before -> do nothing continue go2; } try { rng= getSourceRange(r); if (overlaps(rng, start, end)) { // be tolerant if the delta is not correct, or if // the tree has been updated other than by a delta reuseTreeItem(item, e); continue go2; } else if (rng.getOffset() > start) { if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, (Object) e); } else { // nothing to reuse createTreeItem(w, (Object) e, j); } continue go2; } } catch (JavaModelException x) { // stumbled over deleted element } last= item; } // add at the end of the list if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, e); } else { // nothing to reuse createTreeItem(w, e, -1); } } catch (JavaModelException x) { // the element to be added is not present -> don't add it } } // remove items which haven't been reused Enumeration e= deletions.elements(); while (e.hasMoreElements()) { item= (Item) e.nextElement(); disassociate(item); item.dispose(); } if (doUpdateParent) updateItem(w, delta.getElement()); } }; class LexicalSortingAction extends Action { private JavaElementSorter fSorter= new JavaElementSorter(); public LexicalSortingAction() { super(); setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$ valueChanged(checked, false); } public void run() { valueChanged(isChecked(), true); } private void valueChanged(boolean on, boolean store) { setChecked(on); fOutlineViewer.setSorter(on ? fSorter : null); setToolTipText(on ? JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip.checked") : JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip.unchecked")); //$NON-NLS-2$ //$NON-NLS-1$ setDescription(on ? JavaEditorMessages.getString("JavaOutlinePage.Sort.description.checked") : JavaEditorMessages.getString("JavaOutlinePage.Sort.description.unchecked")); //$NON-NLS-2$ //$NON-NLS-1$ if (store) JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$ } }; class FieldFilter extends ViewerFilter { public boolean select(Viewer viewer, Object parentElement, Object element) { return !(element instanceof IField); } }; class VisibilityFilter extends ViewerFilter { public final static int PUBLIC= 0; public final static int PROTECTED= 1; public final static int PRIVATE= 2; public final static int DEFAULT= 3; public final static int NOT_STATIC= 4; private int fVisibility; public VisibilityFilter(int visibility) { fVisibility= visibility; } /* * 1GEWBY4: ITPJUI:ALL - filtering incorrect on interfaces. */ private boolean belongsToInterface(IMember member) { IType type= member.getDeclaringType(); if (type != null) { try { return type.isInterface(); } catch (JavaModelException x) { // ignore } } return false; } public boolean select(Viewer viewer, Object parentElement, Object element) { if ( !(element instanceof IMember)) return true; if (element instanceof IType) { IType type= (IType) element; IJavaElement parent= type.getParent(); if (parent == null) return true; int elementType= parent.getElementType(); if (elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.CLASS_FILE) return true; } IMember member= (IMember) element; try { int flags= member.getFlags(); switch (fVisibility) { case PUBLIC: /* 1GEWBY4: ITPJUI:ALL - filtering incorrect on interfaces */ return Flags.isPublic(flags) || belongsToInterface(member); case PROTECTED: return Flags.isProtected(flags); case PRIVATE: return Flags.isPrivate(flags); case DEFAULT: { /* 1GEWBY4: ITPJUI:ALL - filtering incorrect on interfaces */ boolean dflt= !(Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)); return dflt ? !belongsToInterface(member) : dflt; } case NOT_STATIC: return !Flags.isStatic(flags); } } catch (JavaModelException x) { } // unreachable return false; } }; class FilterAction extends Action { private ViewerFilter fFilter; private String fCheckedDesc; private String fUncheckedDesc; private String fCheckedTooltip; private String fUncheckedTooltip; private String fPreferenceKey; public FilterAction(ViewerFilter filter, String label, String checkedDesc, String uncheckedDesc, String checkedTooltip, String uncheckedTooltip, String prefKey) { super(); fFilter= filter; setText(label); fCheckedDesc= checkedDesc; fUncheckedDesc= uncheckedDesc; fCheckedTooltip= checkedTooltip; fUncheckedTooltip= uncheckedTooltip; fPreferenceKey= prefKey; boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean(fPreferenceKey); valueChanged(checked, false); } public void run() { valueChanged(isChecked(), true); } private void valueChanged(boolean on, boolean store) { setChecked(on); if (on) { fOutlineViewer.addFilter(fFilter); setToolTipText(fCheckedTooltip); setDescription(fCheckedDesc); } else { fOutlineViewer.removeFilter(fFilter); setToolTipText(fUncheckedTooltip); setDescription(fUncheckedDesc); } if (store) JavaPlugin.getDefault().getPreferenceStore().setValue(fPreferenceKey, on); } }; private IJavaElement fInput; private String fContextMenuID; private Menu fMenu; private JavaOutlineViewer fOutlineViewer; private JavaEditor fEditor; private ListenerList fSelectionChangedListeners= new ListenerList(); private Hashtable fActions= new Hashtable(); private ContextMenuGroup[] fActionGroups; public JavaOutlinePage(String contextMenuID, JavaEditor editor) { super(); Assert.isNotNull(editor); fContextMenuID= contextMenuID; fEditor= editor; } private void fireSelectionChanged(ISelection selection) { SelectionChangedEvent event= new SelectionChangedEvent(this, selection); Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; ++i) ((ISelectionChangedListener) listeners[i]).selectionChanged(event); } /** * @see IPage#createControl */ public void createControl(Composite parent) { Tree tree= new Tree(parent, SWT.MULTI); JavaElementLabelProvider lprovider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_PARAMETERS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_TYPE); fOutlineViewer= new JavaOutlineViewer(tree); fOutlineViewer.setContentProvider(new ChildrenProvider()); fOutlineViewer.setLabelProvider(lprovider); MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { contextMenuAboutToShow(manager); } }); fMenu= manager.createContextMenu(tree); tree.setMenu(fMenu); fActionGroups= new ContextMenuGroup[] { new GenerateGroup(), new JavaSearchGroup(), new ReorgGroup() }; fOutlineViewer.setInput(fInput); fOutlineViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent e) { fireSelectionChanged(e.getSelection()); } }); fOutlineViewer.getControl().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } }); } public void dispose() { if (fEditor == null) return; fEditor.outlinePageClosed(); fEditor= null; Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; i++) fSelectionChangedListeners.remove(listeners[i]); fSelectionChangedListeners= null; if (fMenu != null && !fMenu.isDisposed()) { fMenu.dispose(); fMenu= null; } super.dispose(); } public Control getControl() { if (fOutlineViewer != null) return fOutlineViewer.getControl(); return null; } public void setInput(IJavaElement inputElement) { fInput= inputElement; if (fOutlineViewer != null) fOutlineViewer.setInput(fInput); } public void select(ISourceReference reference) { if (fOutlineViewer != null) { ISelection s= StructuredSelection.EMPTY; if (reference != null) s= new StructuredSelection(reference); fOutlineViewer.setSelection(s, true); } } public void setAction(String actionID, IAction action) { Assert.isNotNull(actionID); if (action == null) fActions.remove(actionID); else fActions.put(actionID, action); } public IAction getAction(String actionID) { Assert.isNotNull(actionID); return (IAction) fActions.get(actionID); } /** * Convenience method to add the action installed under the given actionID to the * specified group of the menu. */ protected void addAction(IMenuManager menu, String group, String actionID) { IAction action= getAction(actionID); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (action.isEnabled()) { IMenuManager subMenu= menu.findMenuUsingPath(group); if (subMenu != null) subMenu.add(action); else menu.appendToGroup(group, action); } } } private void addRefactoring(IMenuManager menu){ MenuManager refactoring= new MenuManager(JavaEditorMessages.getString("JavaOutlinePage.ContextMenu.refactoring.label")); //$NON-NLS-1$ ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fOutlineViewer); if (!refactoring.isEmpty()) menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring); } private void addOpenPerspectiveItem(IMenuManager menu) { ISelection s= getSelection(); if (s.isEmpty() || ! (s instanceof IStructuredSelection)) return; IStructuredSelection selection= (IStructuredSelection)s; if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IType)) return; IType[] input= {(IType)element}; // XXX should get the workbench window form the PartSite IWorkbenchWindow w= JavaPlugin.getActiveWorkbenchWindow(); menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, new OpenHierarchyPerspectiveItem(w, input)); } protected void contextMenuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); if (OrganizeImportsAction.canActionBeAdded(getSelection())) { addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "OrganizeImports"); //$NON-NLS-1$ } addAction(menu, IContextMenuConstants.GROUP_OPEN, "OpenImportDeclaration"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_OPEN, "OpenSuperImplementation"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_SHOW, "ShowInPackageView"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "ReplaceWithEdition"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "AddEdition"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_ADDITIONS, "AddMethodEntryBreakpoint"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_ADDITIONS, "AddWatchpoint"); //$NON_NLS-1$ ContextMenuGroup.add(menu, fActionGroups, fOutlineViewer); addRefactoring(menu); addOpenPerspectiveItem(menu); } /** * @see Page#setFocus() */ public void setFocus() { if (fOutlineViewer != null) fOutlineViewer.getControl().setFocus(); } /** * @see Page#makeContributions(IMenuManager, IToolBarManager, IStatusLineManager) */ public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { if (statusLineManager != null) { StatusBarUpdater updater= new StatusBarUpdater(statusLineManager); addSelectionChangedListener(updater); } Action action= new LexicalSortingAction(); toolBarManager.add(action); action= new FilterAction(new FieldFilter(), JavaEditorMessages.getString("JavaOutlinePage.HideFields.label"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.description.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.description.unchecked"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.tooltip.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideFields.tooltip.unchecked"), "HideFields.isChecked"); //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(action, "fields_co.gif"); //$NON-NLS-1$ toolBarManager.add(action); action= new FilterAction(new VisibilityFilter(VisibilityFilter.NOT_STATIC), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.label"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.description.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.description.unchecked"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.tooltip.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideStaticMembers.tooltip.unchecked"), "HideStaticMembers.isChecked"); //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(action, "static_co.gif"); //$NON-NLS-1$ toolBarManager.add(action); action= new FilterAction(new VisibilityFilter(VisibilityFilter.PUBLIC), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.label"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.description.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.description.unchecked"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.tooltip.checked"), JavaEditorMessages.getString("JavaOutlinePage.HideNonePublicMembers.tooltip.unchecked"), "HideNonePublicMembers.isChecked"); //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(action, "public_co.gif"); //$NON-NLS-1$ toolBarManager.add(action); } /** * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) */ public void addSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.add(listener); } /** * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { fSelectionChangedListeners.remove(listener); } /** * @see ISelectionProvider#getSelection() */ public ISelection getSelection() { if (fOutlineViewer == null) return StructuredSelection.EMPTY; return fOutlineViewer.getSelection(); } /** * @see ISelectionProvider#setSelection(ISelection) */ public void setSelection(ISelection selection) { if (fOutlineViewer != null) fOutlineViewer.setSelection(selection); } /** * Checkes whether a given Java element is an inner type. */ private boolean isInnerType(IJavaElement element) { if (element.getElementType() == IJavaElement.TYPE) { IJavaElement parent= element.getParent(); int type= parent.getElementType(); return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE); } return false; } /** * Handles key events in viewer. */ private void handleKeyPressed(KeyEvent event) { if (event.stateMask != 0) return; IAction action= null; if (event.character == SWT.DEL) { action= getAction("DeleteElement"); //$NON-NLS-1$ if (action instanceof DeleteAction){ //special case - DeleteAction is not a ISelectionChangedListener DeleteAction deleteAction= (DeleteAction)action; deleteAction.update(); if (deleteAction.isEnabled()) deleteAction.run(); return; } } else if (event.keyCode == SWT.F4) { // Special case since Open Type Hierarchy is no action. OpenTypeHierarchyUtil.open(getSelection(), fEditor.getSite().getWorkbenchWindow()); } if (action != null && action.isEnabled()) action.run(); } }
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/core
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportEdit.java
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/core
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
extension/org/eclipse/jdt/internal/corext/textmanipulation/MultiTextEdit.java
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/core
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
extension/org/eclipse/jdt/internal/corext/textmanipulation/SimpleTextEdit.java
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/core
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
extension/org/eclipse/jdt/internal/corext/textmanipulation/TextBufferEditor.java
4,052
Bug 4052 document change infrastructure - missing functionality (1GH2DWC)
AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore.
resolved fixed
fb51769
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
"2001-12-07T10:09:05Z"
"2001-10-11T03:13:20Z"
org.eclipse.jdt.ui/core