issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
timestamp[us, tz=UTC]
report_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
25,183
Bug 25183 AST: ITypeBinding of interface returns constructor
20021018 + jcore for 20021022 LocalCorrectionsQuickFixTest.testUnimplementedMethods Set breakpoint in UnimplementedMethodsCompletionProposal.findUnimplementedInterfaceMethods to see that the ITypeBinding of a interface returns a constructor
verified fixed
9c77ba1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T13:33:21Z
2002-10-22T12:33:20Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest.java
package org.eclipse.jdt.ui.tests.quickfix; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor; /** */ public class QuickFixTest extends TestCase { public static Test suite() { TestSuite suite= new TestSuite(); suite.addTest(new TestSuite(UnresolvedTypesQuickFixTest.class)); suite.addTest(new TestSuite(UnresolvedVariablesQuickFixTest.class)); suite.addTest(new TestSuite(UnresolvedMethodsQuickFixTest.class)); suite.addTest(new TestSuite(ReturnTypeQuickFixTest.class)); suite.addTest(new TestSuite(LocalCorrectionsQuickFixTest.class)); suite.addTest(new TestSuite(ReorgQuickFixTest.class)); suite.addTest(new TestSuite(ModifierCorrectionsQuickFixTest.class)); suite.addTest(new TestSuite(MarkerResolutionTest.class)); return suite; } public QuickFixTest(String name) { super(name); } public static void assertCorrectLabels(List proposals) { for (int i= 0; i < proposals.size(); i++) { ICompletionProposal proposal= (ICompletionProposal) proposals.get(i); String name= proposal.getDisplayString(); if (name == null || name.length() == 0 || name.charAt(0) == '!' || name.indexOf('{') != -1) { assertTrue("wrong proposal label: " + name, false); } if (proposal.getImage() == null) { assertTrue("wrong proposal image", false); } } } public static void assertCorrectContext(CorrectionContext context) { assertTrue("Problem type not marked with lightbulb", JavaCorrectionProcessor.hasCorrections(context.getProblemId())); } public static void assertNumberOf(String name, int nProblems, int nProblemsExpected) { assertTrue("Wrong number of " + name + ", is: " + nProblems + ", expected: " + nProblemsExpected, nProblems == nProblemsExpected); } public static void assertEqualStringsIgnoreOrder(String[] str1, String[] str2) { boolean hasUnmatched= false; loop1: for (int i= 0; i < str1.length; i++) { String s1= str1[i]; for (int k= 0; k < str2.length; k++) { String s2= str2[k]; if (s2 != null && s2.equals(s1)) { str2[k]= null; str1[i]= null; continue loop1; } } hasUnmatched= true; } if (hasUnmatched) { StringBuffer buf= new StringBuffer(); buf.append("Content not as expected: Content is: \n"); for (int i= 0; i < str1.length; i++) { String s1= str1[i]; if (s1 != null) { buf.append(s1); buf.append("\n"); } } buf.append("Expected contents: \n"); for (int i= 0; i < str2.length; i++) { String s2= str2[i]; if (s2 != null) { buf.append(s2); buf.append("\n"); } } } } private static int getDiffPos(String str1, String str2) { int len1= Math.min(str1.length(), str2.length()); int diffPos= -1; for (int i= 0; i < len1; i++) { if (str1.charAt(i) != str2.charAt(i)) { diffPos= i; break; } } if (diffPos == -1 && str1.length() != str2.length()) { diffPos= len1; } return diffPos; } private static final int printRange= 6; public static void assertEqualString(String str1, String str2) { int diffPos= getDiffPos(str1, str2); if (diffPos != -1) { int diffAhead= Math.max(0, diffPos - printRange); int diffAfter= Math.min(str1.length(), diffPos + printRange); String diffStr= str1.substring(diffAhead, diffPos) + '^' + str1.substring(diffPos, diffAfter); assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + str2, false); } } public static void assertEqualStringIgnoreDelim(String str1, String str2) throws IOException { BufferedReader read1= new BufferedReader(new StringReader(str1)); BufferedReader read2= new BufferedReader(new StringReader(str2)); int line= 1; do { String s1= read1.readLine(); String s2= read2.readLine(); if (s1 == null || !s1.equals(s2)) { if (s1 == null && s2 == null) { return; } String diffStr= (s1 == null) ? s2 : s1; assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at line " + line + ": " + diffStr + "\nexpected:\n" + str2, false); } line++; } while (true); } public static TypeDeclaration findTypeDeclaration(CompilationUnit astRoot, String simpleTypeName) { List types= astRoot.types(); for (int i= 0; i < types.size(); i++) { TypeDeclaration elem= (TypeDeclaration) types.get(i); if (simpleTypeName.equals(elem.getName().getIdentifier())) { return elem; } } return null; } public static MethodDeclaration findMethodDeclaration(TypeDeclaration typeDecl, String methodName) { MethodDeclaration[] methods= typeDecl.getMethods(); for (int i= 0; i < methods.length; i++) { if (methodName.equals(methods[i].getName().getIdentifier())) { return methods[i]; } } return null; } public static CorrectionContext getCorrectionContext(ICompilationUnit cu, IProblem problem) { CorrectionContext context= new CorrectionContext(cu); context.initialize(problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1, problem.getID(), problem.getArguments()); return context; } }
19,886
Bug 19886 setProjectJavadocLocation() only in internal package [api] [javadoc]
If You want to set the project javadoc location by API so You have to use an internal class, there is no public interface. see class org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations (Otherwise the method setLibraryJavadocLocation() is public at org.eclipse.jdt.ui.JavaUI - thats ok.)
verified fixed
1a70f57
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T14:21:40Z
2002-06-11T10:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaUI.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.swt.widgets.Shell; 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.ElementListSelectionDialog; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.jdt.core.IBufferFactory; 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.IWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.SharedImages; 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.CompilationUnitDocumentProvider; 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 id of the Java Element Creation action set * (value <code>"org.eclipse.jdt.ui.JavaElementCreationActionSet"</code>). * * @since 2.0 */ public static final String ID_ELEMENT_CREATION_ACTION_SET= "org.eclipse.jdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$ /** * The id of the Java Coding action set * (value <code>"org.eclipse.jdt.ui.CodingActionSet"</code>). * * @since 2.0 */ public static final String ID_CODING_ACTION_SET= "org.eclipse.jdt.ui.CodingActionSet"; //$NON-NLS-1$ /** * The id of the Java action set for open actions * (value <code>"org.eclipse.jdt.ui.A_OpenActionSet"</code>). * * @since 2.0 */ public static final String ID_OPEN_ACTION_SET= "org.eclipse.jdt.ui.A_OpenActionSet"; //$NON-NLS-1$ /** * The id of the Java Search action set * (value <code>org.eclipse.jdt.ui.SearchActionSet"</code>). * * @since 2.0 */ public static final String ID_SEARCH_ACTION_SET= "org.eclipse.jdt.ui.SearchActionSet"; //$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(java.lang.String) * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) */ 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(java.lang.String) * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) */ public static final String ID_TYPE_HIERARCHY= "org.eclipse.jdt.ui.TypeHierarchy"; //$NON-NLS-1$ /** * The id of the Java Browsing Perspective * (value <code>"org.eclipse.jdt.ui.JavaBrowsingPerspective"</code>). * * @since 2.0 */ public static String ID_BROWSING_PERSPECTIVE= "org.eclipse.jdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Projects view * (value <code>"org.eclipse.jdt.ui.ProjectsView"</code>). * * @since 2.0 */ public static String ID_PROJECTS_VIEW= "org.eclipse.jdt.ui.ProjectsView"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Packages view * (value <code>"org.eclipse.jdt.ui.PackagesView"</code>). * * @since 2.0 */ public static String ID_PACKAGES_VIEW= "org.eclipse.jdt.ui.PackagesView"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Types view * (value <code>"org.eclipse.jdt.ui.TypesView"</code>). * * @since 2.0 */ public static String ID_TYPES_VIEW= "org.eclipse.jdt.ui.TypesView"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Members view * (value <code>"org.eclipse.jdt.ui.MembersView"</code>). * * @since 2.0 */ public static String ID_MEMBERS_VIEW= "org.eclipse.jdt.ui.MembersView"; //$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 package (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 valid flags are: * <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; * <code>IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that * packages from required projects should be included as well. * @param filter the initial pattern to filter the set of packages. For example "com" shows * all packages starting with "com". The meta character '?' representing any character and * '*' representing any string are supported. Clients can pass an empty string if no filtering * is required. * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened * * @since 2.0 */ public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException { Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) == (IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS)); IPackageFragmentRoot[] roots= null; if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) { roots= project.getAllPackageFragmentRoots(); } else { 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; } /** * 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 package (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 valid flags are: * <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; * <code>IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that * packages from required projects should be included as well. * @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) throws JavaModelException { return createPackageDialog(parent, project, style, ""); //$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 package (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 initial pattern to filter the set of packages. For example "com" shows * all packages starting with "com". The meta character '?' representing any character and * '*' representing any string are supported. Clients can pass an empty string if no filtering * is required. * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened * * @since 2.0 */ 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; } /** * 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 package (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 * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root) throws JavaModelException { return createPackageDialog(parent, root, ""); //$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 type(s) (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 initial pattern to filter the set of types. For example "Abstract" shows * all types starting with "abstract". The meta character '?' representing any character and * '*' representing any string are supported. Clients can pass an empty string if no filtering * is required. * @exception JavaModelException if the selection dialog could not be opened * * @since 2.0 */ public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) throws JavaModelException { int elementKinds= 0; if (style == IJavaElementSearchConstants.CONSIDER_TYPES) { elementKinds= IJavaSearchConstants.TYPE; } else if (style == IJavaElementSearchConstants.CONSIDER_INTERFACES) { elementKinds= IJavaSearchConstants.INTERFACE; } else if (style == IJavaElementSearchConstants.CONSIDER_CLASSES) { elementKinds= IJavaSearchConstants.CLASS; } else { Assert.isTrue(false, "illegal style"); //$NON-NLS-1$ } if (multipleSelection) { MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, context, elementKinds, scope); dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$ dialog.setFilter(filter); return dialog; } else { TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, elementKinds, scope); dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$ dialog.setFilter(filter); return dialog; } } /** * 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 type(s) (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 * @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) throws JavaModelException { return createTypeDialog(parent, context, scope, style, multipleSelection, "");//$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 type(s) (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_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 initial pattern to filter the set of types containg a main method. For * example "App" shows all types starting with "app". The meta character '?' representing * any character and '*' representing any string are supported. Clients can pass an empty * string if no filtering is required. * @return a new selection dialog * * @since 2.0 */ public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) { if (multipleSelection) { MultiMainTypeSelectionDialog dialog= new MultiMainTypeSelectionDialog(parent, context, scope, style); dialog.setFilter(filter); return dialog; } else { MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(parent, context, scope, style); dialog.setFilter(filter); return dialog; } } /** * 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 type(s) (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_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 * @return a new selection dialog */ public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) { return createMainTypeDialog(parent, context, scope, style, multipleSelection, "");//$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 type(s) (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 element. The element can be a compilation unit * or class file. If there already is an open Java editor for the given element, it is returned. * * @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. The editor simply reveals * the source range denoted by the given source reference. * * @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. If the element is not an instance * of <code>ISourceReference</code> this method result in a NOP. If it is a source * reference no checking is done if the editor displays a compilation unit or class file that * contains the source reference element. The editor simply reveals the source range * denoted by the given element. * * @param part the editor displaying a compilation unit or class file * @param element the element to be revealed * * @since 2.0 */ 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(); } /** * Answers the shared working copies currently registered for the Java plug-in. * * @return the list of shared working copies this plug-in * * @see org.eclipse.jdt.core.JavaCore#getSharedWorkingCopies(org.eclipse.jdt.core.IBufferFactory) * @since 2.0 */ public static IWorkingCopy[] getSharedWorkingCopies() { return JavaCore.getSharedWorkingCopies(getBufferFactory()); } /** * Returns the BufferFactory for the Java UI plug-in. * * @return the BufferFactory for the Java UI plug-in * * @see org.eclipse.jdt.core.IBufferFactory * @since 2.0 */ public static IBufferFactory getBufferFactory() { CompilationUnitDocumentProvider provider= JavaPlugin.getDefault().getCompilationUnitDocumentProvider(); if (provider != null) return provider.getBufferFactory(); return null; } /** * Returns the DocumentProvider used for Java compilation units. * * @return the DocumentProvider for Java compilation units. * * @see IDocumentProvider * @since 2.0 */ public static IDocumentProvider getDocumentProvider() { return JavaPlugin.getDefault().getCompilationUnitDocumentProvider(); } /** * Sets the Javadoc location for an archive with the given path. * * @param archivePath the path of the library; this can be an workspace path * or an external path in case of an external library. * @param url The Javadoc location to set. This location should contain index.html and * a file 'package-list'. * * @since 2.0 */ public static void setLibraryJavadocLocation(IPath archivePath, URL url) { JavaDocLocations.setLibraryJavadocLocation(archivePath, url); } /** * Returns the Javadoc location for an archive or <code>null</code> if no * location is available. * * @param archivePath the path of the library. This can be an workspace path * or an external path in case of an external library. * * @since 2.0 */ public static URL getLibraryJavadocLocation(IPath archivePath) { return JavaDocLocations.getLibraryJavadocLocation(archivePath); } /** * Returns the Javadoc base URL for an element. The base location contains the * index file. This location must not exist. Returns <code>null</code> if no javadoc location * has been attached to the element's library or project. * Example of a returned URL is <i>http://www.junit.org/junit/javadoc</i>. * * @param The element for witch the doc URL is requested. * * @since 2.0 */ public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException { return JavaDocLocations.getJavadocBaseLocation(element); } /** * Returns the Javadoc URL for an element. Example of a returned URL is * <i>http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html</i>. * This returned location must not exist. Returns <code>null</code> if no javadoc location * has been attached to the element's library or project. * * @param The element for witch the doc URL is requested. * @param includeAnchor If set, the URL contains an anchor for member references: * <i>http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult)</i>. Note * that this involves type resolving and is a more expensive call than without anchor. * * @since 2.0 */ public static URL getJavadocLocation(IJavaElement element, boolean includeAnchor) throws JavaModelException { return JavaDocLocations.getJavadocLocation(element, includeAnchor); } }
21,857
Bug 21857 Javadoc code completion does not work for public method of public inner class
Consider the following example, where the cursor is placed at the end of the javadoc comment line. Pressing Ctrl-Space now should complete with "someMethod()", shouldn't it? However, in Build 200206271827, it doesn't. public class TestCompletion { /** * {@link InnerTest#so */ public TestCompletion() { super(); } public class InnerTest { public void someMethod() {} } }
verified fixed
6e9aa8a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T14:45:00Z
2002-07-24T14:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocCompletionEvaluator.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.jdt.core.CompletionRequestorAdapter; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal; import org.eclipse.jdt.internal.ui.text.java.ProposalInfo; public class JavaDocCompletionEvaluator { protected final static String[] fgTagProposals= { "@author", //$NON-NLS-1$ "@deprecated", //$NON-NLS-1$ "@exception", //$NON-NLS-1$ "@link", //$NON-NLS-1$ "@param", //$NON-NLS-1$ "@return", //$NON-NLS-1$ "@see", "@serial", "@serialData", "@serialField", "@since", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "@throws", //$NON-NLS-1$ "@version" //$NON-NLS-1$ }; protected final static String[] fgHTMLProposals= { "<code>", "</code>", //$NON-NLS-2$ //$NON-NLS-1$ "<br>", //$NON-NLS-1$ "<b>", "</b>", //$NON-NLS-2$ //$NON-NLS-1$ "<i>", "</i>", //$NON-NLS-2$ //$NON-NLS-1$ "<pre>", "</pre>" //$NON-NLS-2$ //$NON-NLS-1$ }; private ICompilationUnit fCompilationUnit; private IDocument fDocument; private int fCurrentPos; private int fCurrentLength; private JavaElementLabelProvider fLabelProvider; private List fResult; private boolean fRestrictToMatchingCase; public JavaDocCompletionEvaluator(ICompilationUnit cu, IDocument doc, int pos, int length) { fCompilationUnit= cu; fDocument= doc; fCurrentPos= pos; fCurrentLength= length; fResult= new ArrayList(); fRestrictToMatchingCase= false; } /** * Tells this evaluator to restrict is proposals to those * starting with matching cases. * * @param restrict <code>true</code> if proposals should be restricted */ public void restrictProposalsToMatchingCases(boolean restrict) { fRestrictToMatchingCase= restrict; } private static boolean isWordPart(char ch) { return Character.isJavaIdentifierPart(ch) || (ch == '#') || (ch == '.') || (ch == '/'); } private static int findCharBeforeWord(IDocument doc, int lineBeginPos, int pos) { int currPos= pos - 1; if (currPos > lineBeginPos) { try { while (currPos > lineBeginPos && isWordPart(doc.getChar(currPos))) { currPos--; } return currPos; } catch (BadLocationException e) { } } return pos; } private static int findLastWhitespace(IDocument doc, int lineBeginPos, int pos) { try { int currPos= pos - 1; while (currPos >= lineBeginPos && Character.isWhitespace(doc.getChar(currPos))) { currPos--; } return currPos + 1; } catch (BadLocationException e) { } return pos; } private static int findClosingCharacter(IDocument doc, int pos, int end, char endChar) throws BadLocationException { int curr= pos; while (curr < end && (doc.getChar(curr) != endChar)) { curr++; } if (curr < end) { return curr + 1; } return pos; } private static int findReplaceEndPos(IDocument doc, String newText, String oldText, int pos) { if (oldText.length() == 0 || oldText.equals(newText)) { return pos; } try { IRegion lineInfo= doc.getLineInformationOfOffset(pos); int end= lineInfo.getOffset() + lineInfo.getLength(); if (newText.endsWith(">")) { //$NON-NLS-1$ // for html, search the tag end character return findClosingCharacter(doc, pos, end, '>'); } else { char ch= 0; int pos1= pos; while (pos1 < end && Character.isJavaIdentifierPart(ch= doc.getChar(pos1))) { pos1++; } if (pos1 < end) { // for method references, search the closing bracket if ((ch == '(') && newText.endsWith(")")) { //$NON-NLS-1$ return findClosingCharacter(doc, pos1, end, ')'); } } return pos1; } } catch (BadLocationException e) { e.printStackTrace(); } return pos; } public JavaCompletionProposal[] computeProposals() throws JavaModelException { fLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_POST_QUALIFIED | JavaElementLabelProvider.SHOW_PARAMETERS); try { evalProposals(); return (JavaCompletionProposal[]) fResult.toArray(new JavaCompletionProposal[fResult.size()]); } finally { fLabelProvider.dispose(); fResult.clear(); } } private void evalProposals() throws JavaModelException { try { IRegion info= fDocument.getLineInformationOfOffset(fCurrentPos); int lineBeginPos= info.getOffset(); int word1Begin= findCharBeforeWord(fDocument, lineBeginPos, fCurrentPos); if (word1Begin == fCurrentPos) { return; } char firstChar= fDocument.getChar(word1Begin); if (firstChar == '@') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgTagProposals, JavaPluginImages.IMG_OBJS_JAVADOCTAG); return; } else if (firstChar == '<') { String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin); addProposals(prefix, fgHTMLProposals, JavaPluginImages.IMG_OBJS_HTMLTAG); return; } else if (!Character.isWhitespace(firstChar)) { return; } String prefix= fDocument.get(word1Begin + 1, fCurrentPos - word1Begin - 1); // could be a composed java doc construct (@param, @see ...) int word2End= findLastWhitespace(fDocument, lineBeginPos, word1Begin); if (word2End != lineBeginPos) { // find the word before the prefix int word2Begin= findCharBeforeWord(fDocument, lineBeginPos, word2End); if (fDocument.getChar(word2Begin) == '@') { String tag= fDocument.get(word2Begin, word2End - word2Begin); if (addArgumentProposals(tag, prefix)) { return; } } } addAllTags(prefix); } catch (BadLocationException e) { // ignore } } private boolean prefixMatches(String prefix, String proposal) { if (fRestrictToMatchingCase) { return proposal.startsWith(prefix); } else if (proposal.length() >= prefix.length()) { return prefix.equalsIgnoreCase(proposal.substring(0, prefix.length())); } return false; } private void addAllTags(String prefix) { String jdocPrefix= "@" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgTagProposals.length; i++) { String curr= fgTagProposals[i]; if (prefixMatches(jdocPrefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG), null, 0)); } } String htmlPrefix= "<" + prefix; //$NON-NLS-1$ for (int i= 0; i < fgHTMLProposals.length; i++) { String curr= fgHTMLProposals[i]; if (prefixMatches(htmlPrefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_HTMLTAG), null, 0)); } } } private void addProposals(String prefix, String[] choices, String imageName) { for (int i= 0; i < choices.length; i++) { String curr= choices[i]; if (prefixMatches(prefix, curr)) { fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(imageName), null, 0)); } } } private void addProposals(String prefix, IJavaElement[] choices) { for (int i= 0; i < choices.length; i++) { IJavaElement elem= choices[i]; String curr= getReplaceString(elem); if (prefixMatches(prefix, curr)) { ProposalInfo info= (elem instanceof IMember) ? new ProposalInfo((IMember) elem) : null; fResult.add(createCompletion(curr, prefix, fLabelProvider.getText(elem), fLabelProvider.getImage(elem), info, 0)); } } } 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 { IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos); if ("@see".equals(tag) || "@link".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$ if (elem instanceof IMember) { evalSeeTag((IMember) elem, argument); return true; } } else if ("@param".equals(tag)) { //$NON-NLS-1$ 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$ if (elem instanceof IMethod) { String[] exceptions= ((IMethod)elem).getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { String curr= Signature.toString(exceptions[i]); if (prefixMatches(argument, curr)) { fResult.add(createCompletion(curr, argument, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS), null, 100)); } } evalTypeNameCompletions((IMethod)elem, fCurrentPos - argument.length()); } return true; } else if ("@serialData".equals(tag)) { //$NON-NLS-1$ if (elem instanceof IField) { String name= ((IField)elem).getElementName(); fResult.add(createCompletion(name, argument, name, fLabelProvider.getImage(elem), null, 0)); } return true; } return false; } private void evalSeeTag(IMember elem, String arg) throws JavaModelException { int wordStart= fCurrentPos - arg.length(); int pidx= arg.indexOf('#'); if (pidx == -1) { evalTypeNameCompletions(elem, wordStart); } else { IType parent= null; if (pidx > 0) { // method or field parent= getTypeNameResolve(elem, wordStart, wordStart + pidx); } else { // '@see #foo' parent= (IType) elem.getAncestor(IJavaElement.TYPE); } if (parent != null) { int nidx= arg.indexOf('(', pidx); if (nidx == -1) { nidx= arg.length(); } String prefix= arg.substring(pidx + 1, nidx); addProposals(prefix, parent.getMethods()); addProposals(prefix, parent.getFields()); } } } private void evalTypeNameCompletions(IMember currElem, int wordStart) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(currElem, wordStart, fCurrentPos); if (preparedCU != null) { CompletionRequestorAdapter requestor= new CompletionRequestorAdapter() { public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int start, int end, int severity) { fResult.add(createSeeTypeCompletion(true, start, end, completionName, className, packageName, severity)); } public void acceptInterface(char[] packageName, char[] interfaceName, char[] completionName, int modifiers, int start, int end, int severity) { fResult.add(createSeeTypeCompletion(false, start, end, completionName, interfaceName, packageName, severity)); } public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end, int severity) { fResult.add(createSeeTypeCompletion(true, start, end, completionName, typeName, packageName, severity)); } }; try { preparedCU.codeComplete(fCurrentPos, requestor); if (currElem.getDeclaringType() == null && fCurrentPos > wordStart) { IType type= (IType) currElem; char[] name= type.getElementName().toCharArray(); fResult.add(createSeeTypeCompletion(type.isClass(), wordStart, fCurrentPos, name, name, JavaModelUtil.getTypeContainerName(type).toCharArray(), 50)); } } finally { preparedCU.destroy(); } } } private IType getTypeNameResolve(IMember elem, int wordStart, int wordEnd) throws JavaModelException { ICompilationUnit preparedCU= createPreparedCU(elem, 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(IMember elem, int wordStart, int wordEnd) throws JavaModelException { int startpos= elem.getSourceRange().getOffset(); char[] content= (char[]) fCompilationUnit.getBuffer().getCharacters().clone(); if ((elem.getDeclaringType() == null) && (wordStart + 6 < content.length)) { content[startpos++]= 'i'; content[startpos++]= 'm'; content[startpos++]= 'p'; content[startpos++]= 'o'; content[startpos++]= 'r'; content[startpos++]= 't'; } if (wordStart < content.length) { for (int i= startpos; i < wordStart; i++) { content[i]= ' '; } } ICompilationUnit cu= fCompilationUnit; if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } /* * Explicitly create a new working copy. */ ICompilationUnit newCU= (ICompilationUnit) cu.getWorkingCopy(); newCU.getBuffer().setContents(content); return newCU; } private JavaCompletionProposal createCompletion(String newText, String oldText, String labelText, Image image, ProposalInfo proposalInfo, int severity) { int offset= fCurrentPos - oldText.length(); int length= fCurrentLength + oldText.length(); if (fCurrentLength == 0) length= findReplaceEndPos(fDocument, newText, oldText, fCurrentPos) - offset; JavaCompletionProposal proposal= new JavaCompletionProposal(newText, offset, length, image, labelText, severity); proposal.setProposalInfo(proposalInfo); proposal.setTriggerCharacters( new char[] { '#' }); return proposal; } private JavaCompletionProposal createSeeTypeCompletion(boolean isClass, int start, int end, char[] completion, char[] typeName, char[] containerName, int severity) { ProposalInfo proposalInfo= new ProposalInfo(fCompilationUnit.getJavaProject(), containerName, typeName); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(typeName); if (containerName != null) { nameBuffer.append(" - "); //$NON-NLS-1$ if (containerName.length > 0) { nameBuffer.append(containerName); } else { nameBuffer.append(JavaDocMessages.getString("CompletionEvaluator.default_package")); //$NON-NLS-1$ } } String imageKey= isClass ? JavaPluginImages.IMG_OBJS_CLASS : JavaPluginImages.IMG_OBJS_INTERFACE; int compLen= completion.length; if (compLen > 0 && completion[compLen - 1] == ';') { compLen--; // remove the semicolon from import proposals } JavaCompletionProposal proposal= new JavaCompletionProposal(new String(completion, 0, compLen), start, end - start, JavaPluginImages.get(imageKey), nameBuffer.toString(), severity); proposal.setProposalInfo(proposalInfo); proposal.setTriggerCharacters( new char[] { '#' }); return proposal; } }
24,929
Bug 24929 quick fix: make exception more general [quick fix]
public class DD { void fs() throws MalformedURLException { f(); f1(); } void f() throws IOException{ } void f1() throws MalformedURLException{ } } it'd be cool if qf noticed that it can change the throws clause in fs() to throws IOException (change, not add)
verified fixed
a486bbc
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T15:31:04Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
package org.eclipse.jdt.ui.tests.quickfix; import java.util.ArrayList; import java.util.Hashtable; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor; public class LocalCorrectionsQuickFixTest extends QuickFixTest { private static final Class THIS= LocalCorrectionsQuickFixTest.class; private IJavaProject fJProject1; private IPackageFragmentRoot fSourceFolder; public LocalCorrectionsQuickFixTest(String name) { super(name); } public static Test suite() { if (true) { return new TestSuite(THIS); } else { TestSuite suite= new TestSuite(); suite.addTest(new LocalCorrectionsQuickFixTest("testUnimplementedMethods")); return suite; } } protected void setUp() throws Exception { Hashtable options= JavaCore.getDefaultOptions(); options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE); options.put(JavaCore.FORMATTER_TAB_SIZE, "4"); options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR); JavaCore.setOptions(options); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false); fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); } protected void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); } public void testFieldAccessToStatic() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.File;\n"); buf.append("public class E {\n"); buf.append(" public char foo() {\n"); buf.append(" return (new File(\"x.txt\")).separatorChar;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.File;\n"); buf.append("public class E {\n"); buf.append(" public char foo() {\n"); buf.append(" return File.separatorChar;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testQualifiedAccessToStatic() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Thread t) {\n"); buf.append(" t.sleep(10);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Thread t) {\n"); buf.append(" Thread.sleep(10);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testThisAccessToStatic() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" this.goo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" E.goo();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testCastMissingInVarDecl() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Object o) {\n"); buf.append(" Thread th= o;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Object o) {\n"); buf.append(" Thread th= (Thread) o;\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Object o) {\n"); buf.append(" Object th= o;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastMissingInVarDecl2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("public class Container {\n"); buf.append(" public List[] getLists() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("Container.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Container c) {\n"); buf.append(" ArrayList[] lists= c.getLists();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Container c) {\n"); buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Container c) {\n"); buf.append(" List[] lists= c.getLists();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastMissingInFieldDecl() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" int time= System.currentTimeMillis();\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" int time= (int) System.currentTimeMillis();\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" long time= System.currentTimeMillis();\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastMissingInAssignment() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Iterator;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Iterator iter) {\n"); buf.append(" String str;\n"); buf.append(" str= iter.next();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Iterator;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Iterator iter) {\n"); buf.append(" String str;\n"); buf.append(" str= (String) iter.next();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testCastMissingInExpression() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public String[] foo(List list) {\n"); buf.append(" return list.toArray(new List[list.size()]);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public String[] foo(List list) {\n"); buf.append(" return (String[]) list.toArray(new List[list.size()]);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUncaughtException() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUncaughtException2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public String goo() throws IOException {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo().substring(2);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public String goo() throws IOException {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" goo().substring(2);\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public String goo() throws IOException {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo().substring(2);\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testMultipleUncaughtExceptions() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException, ParseException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 2); // 2 uncaught exceptions CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException, ParseException {\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException, ParseException {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException, ParseException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } catch (ParseException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnneededCatchBlock() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } catch (ParseException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnneededCatchBlockSingle() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnneededCatchBlockWithFinally() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } private boolean BUG_25183= true; public void testUnimplementedMethods() throws Exception { if (BUG_25183) { return ; } IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("import java.io.IOException;\n"); buf.append("public interface Inter {\n"); buf.append(" int getCount(Object[] o) throws IOException;\n"); buf.append("}\n"); pack2.createCompilationUnit("Inter.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import test2.Inter;\n"); buf.append("public class E implements Inter{\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import test2.Inter;\n"); buf.append("public abstract class E implements Inter{\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("\n"); buf.append("import test2.Inter;\n"); buf.append("public class E implements Inter{\n"); buf.append(" public int getCount(Object[] o) throws IOException {\n"); buf.append(" return 0;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } }
24,929
Bug 24929 quick fix: make exception more general [quick fix]
public class DD { void fs() throws MalformedURLException { f(); f1(); } void f() throws IOException{ } void f1() throws MalformedURLException{ } } it'd be cool if qf noticed that it can change the throws clause in fs() to throws IOException (change, not add)
verified fixed
a486bbc
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T15:31:04Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;[email protected]&gt; - Access to static proposal ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.dom.Selection; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil; import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter; import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard; /** */ public class LocalCorrectionsSubProcessor { public static void addCastProposals(ICorrectionContext context, List proposals) throws CoreException { String[] args= context.getProblemArguments(); if (args.length != 2) { return; } ICompilationUnit cu= context.getCompilationUnit(); String castType= args[1]; CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveredNode(); if (!(selectedNode instanceof Expression)) { return; } Expression nodeToCast= (Expression) selectedNode; int parentNodeType= selectedNode.getParent().getNodeType(); if (parentNodeType == ASTNode.ASSIGNMENT) { Assignment assign= (Assignment) selectedNode.getParent(); if (selectedNode.equals(assign.getLeftHandSide())) { nodeToCast= assign.getRightHandSide(); } } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent(); if (selectedNode.equals(frag.getName())) { nodeToCast= frag.getInitializer(); } } ASTRewrite rewrite= new ASTRewrite(astRoot); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image); String simpleCastType= proposal.addImport(castType); Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast); Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE); CastExpression castExpression= astRoot.getAST().newCastExpression(); castExpression.setExpression(expressionCopy); castExpression.setType(typeCopy); rewrite.markAsReplaced(nodeToCast, castExpression); proposal.ensureNoModifications(); proposals.add(proposal); if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent(); ASTNode parent= fragment.getParent(); Type type= null; if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent; if (stmt.fragments().size() == 1) { type= stmt.getType(); } } else if (parent instanceof FieldDeclaration) { FieldDeclaration decl= (FieldDeclaration) parent; if (decl.fragments().size() == 1) { type= decl.getType(); } } if (type != null) { ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings()); String typeName= edit.addImport(args[0]); label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$ ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1); varProposal.getRootTextEdit().add(edit); proposals.add(varProposal); } } } public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveredNode(); if (selectedNode == null) { return; } while (selectedNode != null && !(selectedNode instanceof Statement)) { selectedNode= selectedNode.getParent(); } if (selectedNode == null) { return; } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null); refactoring.setSaveChanges(false); if (refactoring.checkActivationBasics(astRoot, null).isOK()) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image); proposals.add(proposal); } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl == null) { return; } ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength())); TryStatement surroundingTry= (TryStatement) ASTNodes.getParent(selectedNode, ASTNode.TRY_STATEMENT); if (surroundingTry != null) { ASTRewrite rewrite= new ASTRewrite(astRoot); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image); AST ast= astRoot.getAST(); List catchClauses= surroundingTry.catchClauses(); for (int i= 0; i < uncaughtExceptions.length; i++) { String imp= proposal.addImport(uncaughtExceptions[i]); Name name= ASTNodeFactory.newName(ast, imp); SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); var.setName(ast.newSimpleName("e")); var.setType(ast.newSimpleType(name)); CatchClause newClause= ast.newCatchClause(); newClause.setException(var); rewrite.markAsInserted(newClause); catchClauses.add(newClause); } proposal.ensureNoModifications(); proposals.add(proposal); } if (decl instanceof MethodDeclaration) { ASTRewrite rewrite= new ASTRewrite(astRoot); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); AST ast= astRoot.getAST(); MethodDeclaration methodDecl= (MethodDeclaration) decl; List exceptions= methodDecl.thrownExceptions(); for (int i= 0; i < uncaughtExceptions.length; i++) { String imp= proposal.addImport(uncaughtExceptions[i]); Name name= ASTNodeFactory.newName(ast, imp); rewrite.markAsInserted(name); exceptions.add(name); } proposal.ensureNoModifications(); proposals.add(proposal); } } public static void addUnreachableCatchProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) { CatchClause clause= (CatchClause) selectedNode.getParent(); TryStatement tryStatement= (TryStatement) clause.getParent(); ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent()); if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) { rewrite.markAsRemoved(clause); } else { List statements= tryStatement.getBody().statements(); if (statements.size() > 0) { ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1)); rewrite.markAsReplaced(tryStatement, placeholder); } else { rewrite.markAsRemoved(tryStatement); } } String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); proposal.ensureNoModifications(); proposals.add(proposal); } } public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$ ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) { public void apply(IDocument document) { try { NLSRefactoring refactoring= new NLSRefactoring(cu); ExternalizeWizard wizard= new ExternalizeWizard(refactoring); String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$ new RefactoringStarter().activate(refactoring, wizard, dialogTitle, true); } catch (JavaModelException e) { JavaPlugin.log(e); } } }; proposals.add(proposal); TextEdit edit= NLSUtil.createNLSEdit(cu, context.getOffset()); if (edit != null) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE); CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image); nlsProposal.getRootTextEdit().add(edit); proposals.add(nlsProposal); } } /** * A static field or method is accessed using a non-static reference. E.g. * <pre> * File f = new File(); * f.pathSeparator; * </pre> * This correction changes <code>f</code> above to <code>File</code>. * * @param context * @param proposals */ public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveredNode(); if (selectedNode == null) { return; } Expression qualifier= null; if (selectedNode instanceof QualifiedName) { qualifier= ((QualifiedName) selectedNode).getQualifier(); } else if (selectedNode instanceof SimpleName) { ASTNode parent= selectedNode.getParent(); if (parent instanceof FieldAccess) { qualifier= ((FieldAccess) parent).getExpression(); } } else if (selectedNode instanceof MethodInvocation) { qualifier= ((MethodInvocation) selectedNode).getExpression(); } if (qualifier != null) { ITypeBinding typeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding()); if (typeBinding != null) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(typeBinding.getName())); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.changeaccesstostatic.description"); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image); proposal.addImport(typeBinding); proposal.ensureNoModifications(); proposals.add(proposal); } } } public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } ASTNode typeNode= null; if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) { typeNode= selectedNode.getParent(); } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; typeNode= creation.getAnonymousClassDeclaration(); } if (typeNode != null) { UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 0); proposals.add(proposal); } if (typeNode instanceof TypeDeclaration) { TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode; ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration); proposals.add(proposal); } } }
24,919
Bug 24919 quick fix: native methods do not specify a body either [quick fix]
20021016 just like abstract ones - so you can offer removing the modifier
verified fixed
48d74d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T17:24:05Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/ModifierCorrectionsQuickFixTest.java
package org.eclipse.jdt.ui.tests.quickfix; import java.util.ArrayList; import java.util.Hashtable; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor; public class ModifierCorrectionsQuickFixTest extends QuickFixTest { private static final Class THIS= ModifierCorrectionsQuickFixTest.class; private IJavaProject fJProject1; private IPackageFragmentRoot fSourceFolder; public ModifierCorrectionsQuickFixTest(String name) { super(name); } public static Test suite() { if (true) { return new TestSuite(THIS); } else { TestSuite suite= new TestSuite(); suite.addTest(new ModifierCorrectionsQuickFixTest("testInvisibleTypeRequestedFromSuperClass")); return suite; } } protected void setUp() throws Exception { Hashtable options= JavaCore.getDefaultOptions(); options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE); options.put(JavaCore.FORMATTER_TAB_SIZE, "4"); options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR); JavaCore.setOptions(options); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false); fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); } protected void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); } public void testStaticMethodRequestedInSameType1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void xoo() {\n"); buf.append(" }\n"); buf.append(" public static void foo() {\n"); buf.append(" xoo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static void xoo() {\n"); buf.append(" }\n"); buf.append(" public static void foo() {\n"); buf.append(" xoo();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testStaticMethodRequestedInSameType2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void xoo() {\n"); buf.append(" }\n"); buf.append(" public static void foo() {\n"); buf.append(" E.xoo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static void xoo() {\n"); buf.append(" }\n"); buf.append(" public static void foo() {\n"); buf.append(" E.xoo();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testStaticMethodRequestedInOtherType() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class X {\n"); buf.append(" public void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("X.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" X.xoo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class X {\n"); buf.append(" public static void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleMethodRequestedInSuperType() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" private void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends C {\n"); buf.append(" public void foo() {\n"); buf.append(" xoo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" protected void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleSuperMethodRequestedInSuperType() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" private void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends C {\n"); buf.append(" public void foo() {\n"); buf.append(" super.xoo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" protected void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleMethodRequestedInOtherPackage() throws Exception { IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("import java.util.List;\n"); buf.append("public class C {\n"); buf.append(" private void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); pack2.createCompilationUnit("C.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import test2.C;\n"); buf.append("public class E {\n"); buf.append(" public void foo(C c) {\n"); buf.append(" c.xoo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("import java.util.List;\n"); buf.append("public class C {\n"); buf.append(" public void xoo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleConstructorRequestedInOtherType() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" private C() {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" C c= new C();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" C() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleConstructorRequestedInSuperType() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" private C() {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends C {\n"); buf.append(" public E() {\n"); buf.append(" super();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" protected C() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleFieldRequestedInSamePackage1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" private int fXoo;\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(C c) {\n"); buf.append(" c.fXoo= 1;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" int fXoo;\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleFieldRequestedInSamePackage2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" private int fXoo;\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends C {\n"); buf.append(" public void foo() {\n"); buf.append(" fXoo= 1;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" protected int fXoo;\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testNonStaticMethodRequestedInConstructor() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int xoo() { return 1; };\n"); buf.append(" public E(int val) {\n"); buf.append(" }\n"); buf.append(" public E() {\n"); buf.append(" this(xoo());\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private static int xoo() { return 1; };\n"); buf.append(" public E(int val) {\n"); buf.append(" }\n"); buf.append(" public E() {\n"); buf.append(" this(xoo());\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testNonStaticFieldRequestedInConstructor() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int fXoo= 1;\n"); buf.append(" public E(int val) {\n"); buf.append(" }\n"); buf.append(" public E() {\n"); buf.append(" this(fXoo);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private static int fXoo= 1;\n"); buf.append(" public E(int val) {\n"); buf.append(" }\n"); buf.append(" public E() {\n"); buf.append(" this(fXoo);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleTypeRequestedInDifferentPackage() throws Exception { if (false) { System.out.println("testInvisibleTypeRequestedInDifferentPackage: Waiting for release fo bug fix 24406"); return; } IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("class C {\n"); buf.append("}\n"); pack2.createCompilationUnit("C.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" test2.C c= null;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleTypeRequestedFromSuperClass() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" private class CInner {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends C {\n"); buf.append(" public void foo() {\n"); buf.append(" CInner c= null;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" class CInner {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvisibleImport() throws Exception { IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("class C {\n"); buf.append("}\n"); pack2.createCompilationUnit("C.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" test2.C c= null;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testAbstractMethodWithBody() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public abstract class E {\n"); buf.append(" public abstract void foo() {\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public abstract class E {\n"); buf.append(" public void foo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); /* proposal= (CUCorrectionProposal) proposals.get(1); preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public abstract class E {\n"); buf.append(" public abstract void foo();\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); */ } public void testAbstractMethodInNonAbstractClass() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public abstract int foo();\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); IProblem[] problems= astRoot.getProblems(); assertNumberOf("problems", problems.length, 1); CorrectionContext context= getCorrectionContext(cu, problems[0]); assertCorrectContext(context); ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int foo() {\n"); buf.append(" return 0;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); proposal= (CUCorrectionProposal) proposals.get(1); preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public abstract class E {\n"); buf.append(" public abstract int foo();\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } }
24,919
Bug 24919 quick fix: native methods do not specify a body either [quick fix]
20021016 just like abstract ones - so you can offer removing the modifier
verified fixed
48d74d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T17:24:05Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.ui.JavaPluginImages; /** */ public class ModifierCorrectionSubProcessor { public static void addNonAccessibleMemberProposal(ICorrectionContext context, List proposals, boolean visibilityChange) throws JavaModelException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } IBinding binding=null; switch (selectedNode.getNodeType()) { case ASTNode.SIMPLE_NAME: binding= ((SimpleName) selectedNode).resolveBinding(); break; case ASTNode.QUALIFIED_NAME: binding= ((QualifiedName) selectedNode).resolveBinding(); break; case ASTNode.SIMPLE_TYPE: binding= ((SimpleType) selectedNode).resolveBinding(); break; case ASTNode.METHOD_INVOCATION: binding= ((MethodInvocation) selectedNode).getName().resolveBinding(); break; case ASTNode.SUPER_METHOD_INVOCATION: binding= ((SuperMethodInvocation) selectedNode).getName().resolveBinding(); break; case ASTNode.SUPER_FIELD_ACCESS: binding= ((SuperFieldAccess) selectedNode).getName().resolveBinding(); break; case ASTNode.CLASS_INSTANCE_CREATION: binding= ((ClassInstanceCreation) selectedNode).resolveConstructorBinding(); break; case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: binding= ((SuperConstructorInvocation) selectedNode).resolveConstructorBinding(); break; default: return; } ITypeBinding typeBinding= null; String name; if (binding instanceof IMethodBinding) { typeBinding= ((IMethodBinding) binding).getDeclaringClass(); name= binding.getName() + "()"; } else if (binding instanceof IVariableBinding) { typeBinding= ((IVariableBinding) binding).getDeclaringClass(); name= binding.getName(); } else if (binding instanceof ITypeBinding) { typeBinding= (ITypeBinding) binding; name= binding.getName(); } else { return; } if (typeBinding.isFromSource()) { int includedModifiers= 0; int excludedModifiers= 0; String label; if (visibilityChange) { excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC; includedModifiers= getNeededVisibility(selectedNode, typeBinding); label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changevisibility.description", new String[] { name, getVisibilityString(includedModifiers) }); } else { label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertostatic.description", name); includedModifiers= Modifier.STATIC; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), typeBinding); if (targetCU != null) { Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); proposals.add(new ModifierChangeCompletionProposal(label, targetCU, binding, selectedNode, includedModifiers, excludedModifiers, 0, image)); } } } private static String getVisibilityString(int code) { if (Modifier.isPublic(code)) { return "public"; }else if (Modifier.isProtected(code)) { return "protected"; } return "default"; } private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType) { ITypeBinding currNodeBinding= ASTResolving.getBindingOfParentType(currNode); if (currNodeBinding == null) { // import return Modifier.PUBLIC; } ITypeBinding curr= currNodeBinding; while (curr != null) { if (curr.getKey().equals(targetType.getKey())) { return Modifier.PROTECTED; } curr= curr.getSuperclass(); } if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) { return 0; } return Modifier.PUBLIC; } public static void addAbstractMethodProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } MethodDeclaration decl; if (selectedNode instanceof SimpleName) { decl= (MethodDeclaration) selectedNode.getParent(); } else if (selectedNode instanceof MethodDeclaration) { decl= (MethodDeclaration) selectedNode; } else { return; } ASTNode parentType= ASTResolving.findParentType(decl); boolean parentIsAbstract= (parentType instanceof TypeDeclaration) && Modifier.isAbstract(((TypeDeclaration) parentType).getModifiers()); int endPos= decl.getStartPosition() + decl.getLength() - 1; IBuffer buffer= cu.getBuffer(); boolean hasNoBody= buffer.getLength() > endPos && buffer.getChar(endPos) == ';'; if (context.getProblemId() == IProblem.AbstractMethodInAbstractClass || parentIsAbstract) { ASTRewrite rewrite= new ASTRewrite(decl.getParent()); AST ast= astRoot.getAST(); MethodDeclaration modifiedNode= ast.newMethodDeclaration(); modifiedNode.setConstructor(decl.isConstructor()); modifiedNode.setExtraDimensions(decl.getExtraDimensions()); modifiedNode.setModifiers(decl.getModifiers() & ~Modifier.ABSTRACT); rewrite.markAsModified(decl, modifiedNode); if (hasNoBody) { Block newBody= ast.newBlock(); rewrite.markAsInserted(newBody); decl.setBody(newBody); Expression expr= ASTResolving.getInitExpression(decl.getReturnType(), decl.getExtraDimensions()); if (expr != null) { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(expr); newBody.statements().add(returnStatement); } } String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removeabstract.description"); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image); proposal.ensureNoModifications(); proposals.add(proposal); } if (context.getProblemId() == IProblem.AbstractMethodInAbstractClass && (parentType instanceof TypeDeclaration)) { ASTRewriteCorrectionProposal proposal= getMakeTypeStaticProposal(cu, (TypeDeclaration) parentType); proposals.add(proposal); } } public static ASTRewriteCorrectionProposal getMakeTypeStaticProposal(ICompilationUnit cu, TypeDeclaration typeDeclaration) throws CoreException { ASTRewrite rewrite= new ASTRewrite(typeDeclaration.getParent()); AST ast= typeDeclaration.getAST(); TypeDeclaration modifiedNode= ast.newTypeDeclaration(); modifiedNode.setInterface(typeDeclaration.isInterface()); modifiedNode.setModifiers(typeDeclaration.getModifiers() | Modifier.ABSTRACT); rewrite.markAsModified(typeDeclaration, modifiedNode); String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.addabstract.description", typeDeclaration.getName().getIdentifier()); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 3, image); proposal.ensureNoModifications(); return proposal; } }
24,919
Bug 24919 quick fix: native methods do not specify a body either [quick fix]
20021016 just like abstract ones - so you can offer removing the modifier
verified fixed
48d74d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-22T17:24:05Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.compiler.IProblem; /** */ public class QuickFixProcessor implements ICorrectionProcessor { public static boolean hasCorrections(int problemId) { switch (problemId) { case IProblem.UnterminatedString: case IProblem.UnusedImport: case IProblem.DuplicateImport: case IProblem.CannotImportPackage: case IProblem.ConflictingImport: case IProblem.UndefinedMethod: case IProblem.UndefinedConstructor: case IProblem.ParameterMismatch: case IProblem.MethodButWithConstructorName: case IProblem.UndefinedField: case IProblem.UndefinedName: case IProblem.PublicClassMustMatchFileName: case IProblem.PackageIsNotExpectedPackage: case IProblem.UndefinedType: case IProblem.FieldTypeNotFound: case IProblem.ArgumentTypeNotFound: case IProblem.ReturnTypeNotFound: case IProblem.SuperclassNotFound: case IProblem.ExceptionTypeNotFound: case IProblem.InterfaceNotFound: case IProblem.TypeMismatch: case IProblem.UnhandledException: case IProblem.UnreachableCatch: case IProblem.VoidMethodReturnsValue: case IProblem.ShouldReturnValue: case IProblem.MissingReturnType: case IProblem.NonExternalizedStringLiteral: case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: case IProblem.StaticMethodRequested: case IProblem.NonStaticFieldFromStaticInvocation: case IProblem.InstanceMethodDuringConstructorInvocation: case IProblem.InstanceFieldDuringConstructorInvocation: case IProblem.NotVisibleMethod: case IProblem.NotVisibleConstructor: case IProblem.NotVisibleType: case IProblem.SuperclassNotVisible: case IProblem.InterfaceNotVisible: case IProblem.FieldTypeNotVisible: case IProblem.ArgumentTypeNotVisible: case IProblem.ReturnTypeNotVisible: case IProblem.ExceptionTypeNotVisible: case IProblem.NotVisibleField: case IProblem.ImportNotVisible: case IProblem.BodyForAbstractMethod: case IProblem.AbstractMethodInAbstractClass: case IProblem.AbstractMethodMustBeImplemented: return true; default: return false; } } public void process(ICorrectionContext context, List proposals) throws CoreException { int id= context.getProblemId(); if (id == 0) { // no proposals for none-problem locations return; } switch (id) { case IProblem.UnterminatedString: String quoteLabel= CorrectionMessages.getString("JavaCorrectionProcessor.addquote.description"); //$NON-NLS-1$ int pos= InsertCorrectionProposal.moveBack(context.getOffset() + context.getLength(), context.getOffset(), "\n\r", context.getCompilationUnit()); //$NON-NLS-1$ proposals.add(new InsertCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, "\"", 0)); //$NON-NLS-1$ break; case IProblem.UnusedImport: case IProblem.DuplicateImport: case IProblem.CannotImportPackage: case IProblem.ConflictingImport: ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, proposals); break; case IProblem.UndefinedMethod: UnresolvedElementsSubProcessor.getMethodProposals(context, false, proposals); break; case IProblem.UndefinedConstructor: UnresolvedElementsSubProcessor.getConstructorProposals(context, proposals); break; case IProblem.ParameterMismatch: UnresolvedElementsSubProcessor.getMethodProposals(context, true, proposals); break; case IProblem.MethodButWithConstructorName: ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, proposals); break; case IProblem.UndefinedField: case IProblem.UndefinedName: UnresolvedElementsSubProcessor.getVariableProposals(context, proposals); break; case IProblem.PublicClassMustMatchFileName: ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(context, proposals); break; case IProblem.PackageIsNotExpectedPackage: ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(context, proposals); break; case IProblem.UndefinedType: case IProblem.FieldTypeNotFound: case IProblem.ArgumentTypeNotFound: case IProblem.ReturnTypeNotFound: case IProblem.SuperclassNotFound: case IProblem.ExceptionTypeNotFound: case IProblem.InterfaceNotFound: UnresolvedElementsSubProcessor.getTypeProposals(context, proposals); break; case IProblem.TypeMismatch: LocalCorrectionsSubProcessor.addCastProposals(context, proposals); break; case IProblem.UnhandledException: LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, proposals); break; case IProblem.UnreachableCatch: LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, proposals); break; case IProblem.VoidMethodReturnsValue: ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, proposals); break; case IProblem.MissingReturnType: ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, proposals); break; case IProblem.ShouldReturnValue: ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, proposals); break; case IProblem.NonExternalizedStringLiteral: LocalCorrectionsSubProcessor.addNLSProposals(context, proposals); break; case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: LocalCorrectionsSubProcessor.addInstanceAccessToStaticProposals(context, proposals); break; case IProblem.StaticMethodRequested: case IProblem.NonStaticFieldFromStaticInvocation: case IProblem.InstanceMethodDuringConstructorInvocation: case IProblem.InstanceFieldDuringConstructorInvocation: ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, false); break; case IProblem.NotVisibleMethod: case IProblem.NotVisibleConstructor: case IProblem.NotVisibleType: case IProblem.SuperclassNotVisible: case IProblem.InterfaceNotVisible: case IProblem.FieldTypeNotVisible: case IProblem.ArgumentTypeNotVisible: case IProblem.ReturnTypeNotVisible: case IProblem.ExceptionTypeNotVisible: case IProblem.NotVisibleField: case IProblem.ImportNotVisible: ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, true); break; case IProblem.BodyForAbstractMethod: case IProblem.AbstractMethodInAbstractClass: ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, proposals); break; case IProblem.AbstractMethodMustBeImplemented: LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, proposals); break; default: } } }
25,031
Bug 25031 [Dialogs] Bogus progress bar after canceling paste
Build 20021016 1) Select a file in the resource navigator 2) Right click and choose copy 3) Right click again and choose paste -> A dialog comes up asking for a new file name 4) Click cancel on this dialog. -> A progress bar appears in the status line. The message says, "Performing changes". The progress bar fills up immediately and then stays visible indefinitely. It only disappears when you start a new operation (such as a build).
verified fixed
89b2d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-23T14:18:17Z
2002-10-17T21:26:40Z
org.eclipse.jdt.ui/ui
25,031
Bug 25031 [Dialogs] Bogus progress bar after canceling paste
Build 20021016 1) Select a file in the resource navigator 2) Right click and choose copy 3) Right click again and choose paste -> A dialog comes up asking for a new file name 4) Click cancel on this dialog. -> A progress bar appears in the status line. The message says, "Performing changes". The progress bar fills up immediately and then stays visible indefinitely. It only disappears when you start a new operation (such as a build).
verified fixed
89b2d1f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-23T14:18:17Z
2002-10-17T21:26:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/PerformChangeOperation.java
24,571
Bug 24571 Move To Top Level: puts several statements on one line [refactoring]
Using 2.1 I20021008 Tried the "move to top level" refactoring on a static inner class. The new top level class has the package and import statements on one line. I'm guessing the fact I'm editing a file with unix line terminators could have something to do with it: Attaching new top level class.
verified fixed
4b0b7ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-23T14:51:49Z
2002-10-09T13:26:40Z
org.eclipse.jdt.ui/core
24,571
Bug 24571 Move To Top Level: puts several statements on one line [refactoring]
Using 2.1 I20021008 Tried the "move to top level" refactoring on a static inner class. The new top level class has the package and import statements on one line. I'm guessing the fact I'm editing a file with unix line terminators could have something to do with it: Attaching new top level class.
verified fixed
4b0b7ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-23T14:51:49Z
2002-10-09T13:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java
24,915
Bug 24915 Use Supertype Where Possible: should update UI when checkbox changes [refactoring]
Build 20021016 1. Start Use Supertype Where Possible refactoring 2. Select a supertype where no possible updates can be found 3. Press Next 4. Go Back 5. Toggle the checkbox "Use the selected supertype in "instance of" expressions ==> not sure whether this should update the view (e.g. allow to start again with above type)
verified fixed
817dd4d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-23T16:22:08Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui
24,915
Bug 24915 Use Supertype Where Possible: should update UI when checkbox changes [refactoring]
Build 20021016 1. Start Use Supertype Where Possible refactoring 2. Select a supertype where no possible updates can be found 3. Press Next 4. Go Back 5. Toggle the checkbox "Use the selected supertype in "instance of" expressions ==> not sure whether this should update the view (e.g. allow to start again with above type)
verified fixed
817dd4d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-23T16:22:08Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/UseSupertypeInputPage.java
25,129
Bug 25129 IAE in eating code assist
Don't have a reproducible case yet but do see it quite regularly. Have eating code assist enabled. java.lang.IllegalArgumentException: Index out of bounds at org.eclipse.swt.SWT.error(SWT.java:2125) at org.eclipse.swt.SWT.error(SWT.java:2071) at org.eclipse.swt.custom.StyledText.setStyleRange(StyledText.java:7168) at org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal.updateStyle (JavaCompletionProposal.java:498) at org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal.selected (JavaCompletionProposal.java:506) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposal (CompletionProposalPopup.java:573) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.setProposals (CompletionProposalPopup.java:430) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$15 (CompletionProposalPopup.java:406) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$6.run (CompletionProposalPopup.java:630) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:31) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:94) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1599) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1372) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1420) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
02e1360
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-28T15:57:59Z
2002-10-21T17:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProposal.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; public class JavaCompletionProposal implements IJavaCompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2 { private String fDisplayString; private String fReplacementString; private int fReplacementOffset; private int fReplacementLength; private int fCursorPosition; private Image fImage; private IContextInformation fContextInformation; private int fContextInformationPosition; private ProposalInfo fProposalInfo; private char[] fTriggerCharacters; protected boolean fToggleEating; protected ITextViewer fTextViewer; private int fRelevance; private StyleRange fRememberedStyleRange; /** * Creates a new completion proposal. All fields are initialized based on the provided information. * * @param replacementString the actual string to be inserted into the document * @param replacementOffset the offset of the text to be replaced * @param replacementLength the length of the text to be replaced * @param image the image to display for this proposal * @param displayString the string to be displayed for the proposal * If set to <code>null</code>, the replacement string will be taken as display string. */ public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) { this(replacementString, replacementOffset, replacementLength, image, displayString, relevance, null); } /** * Creates a new completion proposal. All fields are initialized based on the provided information. * * @param replacementString the actual string to be inserted into the document * @param replacementOffset the offset of the text to be replaced * @param replacementLength the length of the text to be replaced * @param image the image to display for this proposal * @param displayString the string to be displayed for the proposal * @param viewer the text viewer for which this proposal is computed, may be <code>null</code> * If set to <code>null</code>, the replacement string will be taken as display string. */ public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, ITextViewer viewer) { Assert.isNotNull(replacementString); Assert.isTrue(replacementOffset >= 0); Assert.isTrue(replacementLength >= 0); fReplacementString= replacementString; fReplacementOffset= replacementOffset; fReplacementLength= replacementLength; fImage= image; fDisplayString= displayString != null ? displayString : replacementString; fRelevance= relevance; fTextViewer= viewer; fCursorPosition= replacementString.length(); fContextInformation= null; fContextInformationPosition= -1; fTriggerCharacters= null; fProposalInfo= null; } /** * Sets the context information. * @param contentInformation The context information associated with this proposal */ public void setContextInformation(IContextInformation contextInformation) { fContextInformation= contextInformation; fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1); } /** * Sets the trigger characters. * @param triggerCharacters The set of characters which can trigger the application of this completion proposal */ public void setTriggerCharacters(char[] triggerCharacters) { fTriggerCharacters= triggerCharacters; } /** * Sets the proposal info. * @param additionalProposalInfo The additional information associated with this proposal or <code>null</code> */ public void setProposalInfo(ProposalInfo proposalInfo) { fProposalInfo= proposalInfo; } /** * Sets the cursor position relative to the insertion offset. By default this is the length of the completion string * (Cursor positioned after the completion) * @param cursorPosition The cursorPosition to set */ public void setCursorPosition(int cursorPosition) { Assert.isTrue(cursorPosition >= 0); fCursorPosition= cursorPosition; fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1); } /* * @see ICompletionProposalExtension#apply(IDocument, char, int) */ public void apply(IDocument document, char trigger, int offset) { try { // patch replacement length int delta= offset - (fReplacementOffset + fReplacementLength); if (delta > 0) fReplacementLength += delta; String string; if (trigger == (char) 0) { string= fReplacementString; } else { StringBuffer buffer= new StringBuffer(fReplacementString); // fix for PR #5533. Assumes that no eating takes place. if ((fCursorPosition > 0 && fCursorPosition <= buffer.length() && buffer.charAt(fCursorPosition - 1) != trigger)) { buffer.insert(fCursorPosition, trigger); ++fCursorPosition; } string= buffer.toString(); } replace(document, fReplacementOffset, fReplacementLength, string); if (fTextViewer != null && string != null) { int index= string.indexOf("()"); //$NON-NLS-1$ if (index != -1) { IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore(); if (preferenceStore.getBoolean(CompilationUnitEditor.CLOSE_BRACKETS)) { int newOffset= fReplacementOffset + index; LinkedPositionManager manager= new LinkedPositionManager(document); manager.addPosition(newOffset + 1, 0); LinkedPositionUI editor= new LinkedPositionUI(fTextViewer, manager); editor.setExitPolicy(new ExitPolicy(')')); editor.setFinalCaretOffset(newOffset + 2); editor.enter(); } } } } catch (BadLocationException x) { // ignore } } private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { final char fExitCharacter; public ExitPolicy(char exitCharacter) { fExitCharacter= exitCharacter; } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (manager.anyPositionIncludes(offset, length)) return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false); else return new ExitFlags(LinkedPositionUI.COMMIT, true); } switch (event.character) { case '\b': if (manager.getFirstPosition().length == 0) return new ExitFlags(0, true); else return null; case '\n': case '\r': return new ExitFlags(LinkedPositionUI.COMMIT, true); default: return null; } } } // #6410 - File unchanged but dirtied by code assist private void replace(IDocument document, int offset, int length, String string) throws BadLocationException { if (!document.get(offset, length).equals(string)) document.replace(offset, length, string); } /* * @see ICompletionProposal#apply */ public void apply(IDocument document) { apply(document, (char) 0, fReplacementOffset + fReplacementLength); } /* * @see ICompletionProposal#getSelection */ public Point getSelection(IDocument document) { return new Point(fReplacementOffset + fCursorPosition, 0); } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return fContextInformation; } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return fImage; } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { return fDisplayString; } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { if (fProposalInfo != null) { return fProposalInfo.getInfo(); } return null; } /* * @see ICompletionProposalExtension#getTriggerCharacters() */ public char[] getTriggerCharacters() { return fTriggerCharacters; } /* * @see ICompletionProposalExtension#getContextInformationPosition() */ public int getContextInformationPosition() { return fReplacementOffset + fContextInformationPosition; } /** * Gets the replacement offset. * @return Returns a int */ public int getReplacementOffset() { return fReplacementOffset; } /** * Sets the replacement offset. * @param replacementOffset The replacement offset to set */ public void setReplacementOffset(int replacementOffset) { Assert.isTrue(replacementOffset >= 0); fReplacementOffset= replacementOffset; } /** * Gets the replacement length. * @return Returns a int */ public int getReplacementLength() { return fReplacementLength; } /** * Sets the replacement length. * @param replacementLength The replacementLength to set */ public void setReplacementLength(int replacementLength) { Assert.isTrue(replacementLength >= 0); fReplacementLength= replacementLength; } /** * Gets the replacement string. * @return Returns a String */ public String getReplacementString() { return fReplacementString; } /** * Sets the replacement string. * @param replacementString The replacement string to set */ public void setReplacementString(String replacementString) { fReplacementString= replacementString; } /** * Sets the image. * @param image The image to set */ public void setImage(Image image) { fImage= image; } /* * @see ICompletionProposalExtension#isValidFor(IDocument, int) */ public boolean isValidFor(IDocument document, int offset) { return validate(document, offset, null); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent) */ public boolean validate(IDocument document, int offset, DocumentEvent event) { if (offset < fReplacementOffset) return false; /* * See http://dev.eclipse.org/bugs/show_bug.cgi?id=17667 String word= fReplacementString; */ boolean validated= startsWith(document, offset, fDisplayString); if (validated && event != null) { // adapt replacement range to document change int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength; fReplacementLength += delta; } return validated; } /** * Gets the proposal's relevance. * @return Returns a int */ public int getRelevance() { return fRelevance; } /** * Sets the proposal's relevance. * @param relevance The relevance to set */ public void setRelevance(int relevance) { fRelevance= relevance; } /** * Returns <code>true</code> if a words starts with the code completion prefix in the document, * <code>false</code> otherwise. */ protected boolean startsWith(IDocument document, int offset, String word) { int wordLength= word == null ? 0 : word.length(); if (offset > fReplacementOffset + wordLength) return false; try { int length= offset - fReplacementOffset; String start= document.get(fReplacementOffset, length); return word.substring(0, length).equalsIgnoreCase(start); } catch (BadLocationException x) { } return false; } private static boolean insertCompletion() { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); return preference.getBoolean(ContentAssistPreference.INSERT_COMPLETION); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension1#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document= viewer.getDocument(); fToggleEating= (stateMask & SWT.CTRL) != 0; if (insertCompletion() ^ fToggleEating) fReplacementLength= offset - fReplacementOffset; apply(document, trigger, offset); fToggleEating= false; } private static Color getForegroundColor(StyledText text) { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.COMPLETION_REPLACEMENT_FOREGROUND); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private static Color getBackgroundColor(StyledText text) { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.COMPLETION_REPLACEMENT_BACKGROUND); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private void repairPresentation(ITextViewer viewer) { if (fRememberedStyleRange != null && viewer instanceof ITextViewerExtension2) { // attempts to reduce the redraw area ITextViewerExtension2 viewer2= (ITextViewerExtension2) viewer; viewer2.invalidateTextPresentation(fRememberedStyleRange.start, fRememberedStyleRange.length); } else viewer.invalidateTextPresentation(); } private void updateStyle(ITextViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; fRememberedStyleRange= null; IRegion visibleRegion= viewer.getVisibleRegion(); int caretOffset= text.getCaretOffset() + visibleRegion.getOffset(); // patch int delta= caretOffset - (fReplacementOffset + fReplacementLength); if (delta > 0) fReplacementLength += delta; if (caretOffset >= fReplacementOffset + fReplacementLength) { repairPresentation(viewer); return; } int offset= caretOffset - visibleRegion.getOffset(); int length= fReplacementOffset + fReplacementLength - caretOffset; Color foreground= getForegroundColor(text); Color background= getBackgroundColor(text); repairPresentation(viewer); fRememberedStyleRange= new StyleRange(offset, length, foreground, background); text.setStyleRange(fRememberedStyleRange); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(ITextViewer, boolean) */ public void selected(ITextViewer viewer, boolean smartToggle) { if (!insertCompletion() ^ smartToggle) updateStyle(viewer); else { repairPresentation(viewer); fRememberedStyleRange= null; } } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(ITextViewer) */ public void unselected(ITextViewer viewer) { repairPresentation(viewer); fRememberedStyleRange= null; } }
25,069
Bug 25069 Reuse editor in Search view does not check it the editor is pinned.
null
resolved fixed
afe3d03
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-28T17:03:56Z
2002-10-18T16:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/GotoMarkerAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.search; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.search.ui.ISearchResultView; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.search.ui.SearchUI; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IPackagesViewPart; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.InternalClassFileEditorInput; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.SelectionUtil; public class GotoMarkerAction extends Action { private IEditorPart fEditor; public GotoMarkerAction(){ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GOTO_MARKER_ACTION); } public void run() { ISearchResultView view= SearchUI.getSearchResultView(); Object element= SelectionUtil.getSingleElement(view.getSelection()); if (element instanceof ISearchResultViewEntry) { ISearchResultViewEntry entry= (ISearchResultViewEntry)element; show(entry.getSelectedMarker()); } } private void show(IMarker marker) { IResource resource= marker.getResource(); if (resource == null || !resource.exists()) return; IWorkbenchPage wbPage= JavaPlugin.getActivePage(); IJavaElement javaElement= SearchUtil.getJavaElement(marker); // if (javaElement == null) { // beep(); // return; // } if (javaElement != null && javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { // Goto packages view try { IViewPart view= wbPage.showView(JavaUI.ID_PACKAGES); if (view instanceof IPackagesViewPart) ((IPackagesViewPart)view).selectAndReveal(javaElement); } catch (PartInitException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$ } } else { if (SearchUI.reuseEditor()) showWithReuse(marker, resource, javaElement, wbPage); else showWithoutReuse(marker, javaElement, wbPage); } } private void showWithoutReuse(IMarker marker, IJavaElement javaElement, IWorkbenchPage wbPage) { IEditorPart editor= null; try { Object objectToOpen= javaElement; if (objectToOpen == null) objectToOpen= marker.getResource(); editor= EditorUtility.openInEditor(objectToOpen, false); } catch (PartInitException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$ } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$ } if (editor != null) editor.gotoMarker(marker); } private void showWithReuse(IMarker marker, IResource resource, IJavaElement javaElement, IWorkbenchPage wbPage) { if (javaElement == null || !isBinary(javaElement)) { if (resource instanceof IFile) showInEditor(marker, wbPage, new FileEditorInput((IFile)resource), JavaUI.ID_CU_EDITOR); } else { IClassFile cf= getClassFile(javaElement); if (cf != null) showInEditor(marker, wbPage, new InternalClassFileEditorInput(cf), JavaUI.ID_CF_EDITOR); } } private void showInEditor(IMarker marker, IWorkbenchPage page, IEditorInput input, String editorId) { IEditorPart editor= page.findEditor(input); if (editor == null) { if (fEditor != null && !fEditor.isDirty()) page.closeEditor(fEditor, false); try { editor= page.openEditor(input, editorId, false); } catch (PartInitException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$ return; } } else { page.bringToTop(editor); } if (editor != null) { editor.gotoMarker(marker); fEditor = editor; } } private void gotoPackagesView(IJavaElement javaElement, IWorkbenchPage wbPage) { try { IViewPart view= wbPage.showView(JavaUI.ID_PACKAGES); if (view instanceof IPackagesViewPart) ((IPackagesViewPart)view).selectAndReveal(javaElement); } catch (PartInitException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$ } } private IClassFile getClassFile(IJavaElement jElement) { if (jElement instanceof IMember) return ((IMember)jElement).getClassFile(); return null; } private boolean isBinary(IJavaElement jElement) { if (jElement instanceof IMember) return ((IMember)jElement).isBinary(); return false; } private void beep() { Shell shell= JavaPlugin.getActiveWorkbenchShell(); if (shell != null && shell.getDisplay() != null) shell.getDisplay().beep(); } }
25,211
Bug 25211 Widget Is Disposed from java preference page
Build 20021018 I got the following "Widget is disposed" exception repeatedly when browsing the Java preference pages: !MESSAGE Widget is disposed !STACK 0 org.eclipse.swt.SWTException: Widget is disposed at org.eclipse.swt.SWT.error(SWT.java:2139) at org.eclipse.swt.SWT.error(SWT.java:2071) at org.eclipse.swt.widgets.Widget.error(Widget.java:294) at org.eclipse.swt.widgets.Control.getDisplay(Control.java:1268) at org.eclipse.swt.widgets.Widget.isValidThread(Widget.java:476) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:232) at org.eclipse.swt.widgets.List.select(List.java:946) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage$19.run(JavaEditorPreferencePage.java:1047) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:31) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:94) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1374) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1246) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1420) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) !ENTRY org.eclipse.ui 4 4 Oct 22, 2002 14:38:46.78 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Oct 22, 2002 14:38:46.84 !MESSAGE Widget is disposed !STACK 0 org.eclipse.swt.SWTException: Widget is disposed at org.eclipse.swt.SWT.error(SWT.java:2139) at org.eclipse.swt.SWT.error(SWT.java:2071) at org.eclipse.swt.widgets.Widget.error(Widget.java:294) at org.eclipse.swt.widgets.Control.getDisplay(Control.java:1268) at org.eclipse.swt.widgets.Widget.isValidThread(Widget.java:476) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:232) at org.eclipse.swt.widgets.List.select(List.java:946) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage$20.run(JavaEditorPreferencePage.java:1057) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:31) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:94) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1374) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1246) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1420) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
ab1de64
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-28T18:26:09Z
2002-10-22T18:06:40Z
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.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.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.JavaUIMessages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; 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 static final String BOLD= "_bold"; //$NON-NLS-1$ public static final String PREF_SHOW_TEMP_PROBLEMS= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ public static final String PREF_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ public final OverlayPreferenceStore.OverlayKey[] fKeys= new OverlayPreferenceStore.OverlayKey[] { new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH), 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_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.STRING, CompilationUnitEditor.CURRENT_LINE_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.CURRENT_LINE), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.PRINT_MARGIN_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, CompilationUnitEditor.PRINT_MARGIN_COLUMN), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.PRINT_MARGIN), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.LINKED_POSITION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.ERROR_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.ERROR_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.WARNING_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.WARNING_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.MARKER_INDICATION_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.MARKER_INDICATION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.ERROR_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.WARNING_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.MARKER_INDICATION_IN_OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, JavaEditorPreferencePage.PREF_SHOW_TEMP_PROBLEMS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, JavaEditorPreferencePage.PREF_SYNC_OUTLINE_ON_CURSOR_MOVE), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitDocumentProvider.HANDLE_TEMPORARY_PROBLEMS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.OVERVIEW_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, JavaEditor.LINE_NUMBER_COLOR), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, JavaEditor.LINE_NUMBER_RULER), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.SPACES_FOR_TABS), 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.COMPLETION_REPLACEMENT_BACKGROUND), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.COMPLETION_REPLACEMENT_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), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.INSERT_COMPLETION), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.FILL_METHOD_ARGUMENTS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.GUESS_METHOD_ARGUMENTS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.CLOSE_STRINGS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.CLOSE_BRACKETS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.CLOSE_JAVADOCS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.WRAP_STRINGS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.ADD_JAVADOC_TAGS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.FORMAT_JAVADOCS), new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END) }; private final String[][] fSyntaxColorListModel= new String[][] { { JavaUIMessages.getString("JavaEditorPreferencePage.multiLineComment"), IJavaColorConstants.JAVA_MULTI_LINE_COMMENT }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.singleLineComment"), IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.keywords"), IJavaColorConstants.JAVA_KEYWORD }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.strings"), IJavaColorConstants.JAVA_STRING }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.others"), IJavaColorConstants.JAVA_DEFAULT }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), IJavaColorConstants.JAVADOC_KEYWORD }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), IJavaColorConstants.JAVADOC_TAG }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.javaDocLinks"), IJavaColorConstants.JAVADOC_LINK }, //$NON-NLS-1$ { JavaUIMessages.getString("JavaEditorPreferencePage.javaDocOthers"), IJavaColorConstants.JAVADOC_DEFAULT } //$NON-NLS-1$ }; private final String[][] fAppearanceColorListModel= new String[][] { {JavaUIMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), JavaEditor.LINE_NUMBER_COLOR}, //$NON-NLS-1$ {JavaUIMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), CompilationUnitEditor.MATCHING_BRACKETS_COLOR}, //$NON-NLS-1$ {JavaUIMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), CompilationUnitEditor.CURRENT_LINE_COLOR}, //$NON-NLS-1$ {JavaUIMessages.getString("JavaEditorPreferencePage.printMarginColor2"), CompilationUnitEditor.PRINT_MARGIN_COLOR}, //$NON-NLS-1$ {JavaUIMessages.getString("JavaEditorPreferencePage.findScopeColor2"), AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE}, //$NON-NLS-1$ {JavaUIMessages.getString("JavaEditorPreferencePage.linkedPositionColor2"), CompilationUnitEditor.LINKED_POSITION_COLOR}, //$NON-NLS-1$ }; private final String[][] fProblemIndicationColorListModel= new String[][] { {"Errors", CompilationUnitEditor.ERROR_INDICATION_COLOR}, {"Warnings", CompilationUnitEditor.WARNING_INDICATION_COLOR}, {"Markers", CompilationUnitEditor.MARKER_INDICATION_COLOR} }; 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 ArrayList fNumberFields= new ArrayList(); private ModifyListener fNumberFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { numberFieldChanged((Text) e.widget); } }; private WorkbenchChainedTextFontFieldEditor fFontEditor; private List fSyntaxColorList; private List fAppearanceColorList; private List fProblemIndicationColorList; private ColorEditor fSyntaxForegroundColorEditor; private ColorEditor fAppearanceForegroundColorEditor; private ColorEditor fProblemIndicationForegroundColorEditor; private ColorEditor fBackgroundColorEditor; private Button fBackgroundDefaultRadioButton; private Button fBackgroundCustomRadioButton; private Button fBackgroundColorButton; private Button fBoldCheckBox; private Button fAddJavaDocTagsButton; private Button fGuessMethodArgumentsButton; private SourceViewer fPreviewViewer; private Color fBackgroundColor; private Control fAutoInsertDelayText; private Control fAutoInsertJavaTriggerText; private Control fAutoInsertJavaDocTriggerText; public JavaEditorPreferencePage() { setDescription(JavaUIMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys); } public static void initDefaults(IPreferenceStore store) { /* * Ensure that the display is accessed only in the UI thread. * Ensure that there are no side effects of switching the thread. */ final RGB[] rgbs= new RGB[3]; final Display display= Display.getDefault(); display.syncExec(new Runnable() { public void run() { Color c= display.getSystemColor(SWT.COLOR_GRAY); rgbs[0]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND); rgbs[1]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); rgbs[2]= c.getRGB(); } }); /* * Go on in whatever thread this is. */ store.setDefault(CompilationUnitEditor.MATCHING_BRACKETS, true); PreferenceConverter.setDefault(store, CompilationUnitEditor.MATCHING_BRACKETS_COLOR, rgbs[0]); store.setDefault(CompilationUnitEditor.CURRENT_LINE, true); PreferenceConverter.setDefault(store, CompilationUnitEditor.CURRENT_LINE_COLOR, new RGB(225, 235, 224)); store.setDefault(CompilationUnitEditor.PRINT_MARGIN, false); store.setDefault(CompilationUnitEditor.PRINT_MARGIN_COLUMN, 80); PreferenceConverter.setDefault(store, CompilationUnitEditor.PRINT_MARGIN_COLOR, new RGB(176, 180 , 185)); PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE, new RGB(185, 176 , 180)); store.setDefault(CompilationUnitEditor.ERROR_INDICATION, true); PreferenceConverter.setDefault(store, CompilationUnitEditor.ERROR_INDICATION_COLOR, new RGB(255, 0 , 128)); store.setDefault(CompilationUnitEditor.WARNING_INDICATION, true); PreferenceConverter.setDefault(store, CompilationUnitEditor.WARNING_INDICATION_COLOR, new RGB(244, 200 , 45)); store.setDefault(CompilationUnitEditor.MARKER_INDICATION, true); PreferenceConverter.setDefault(store, CompilationUnitEditor.MARKER_INDICATION_COLOR, new RGB(0, 128, 255)); store.setDefault(CompilationUnitEditor.ERROR_INDICATION_IN_OVERVIEW_RULER, true); store.setDefault(CompilationUnitEditor.WARNING_INDICATION_IN_OVERVIEW_RULER, true); store.setDefault(CompilationUnitEditor.MARKER_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(JavaEditorPreferencePage.PREF_SHOW_TEMP_PROBLEMS, true); store.setDefault(JavaEditorPreferencePage.PREF_SYNC_OUTLINE_ON_CURSOR_MOVE, false); store.setDefault(CompilationUnitDocumentProvider.HANDLE_TEMPORARY_PROBLEMS, true); store.setDefault(CompilationUnitEditor.OVERVIEW_RULER, true); store.setDefault(JavaEditor.LINE_NUMBER_RULER, false); PreferenceConverter.setDefault(store, JavaEditor.LINE_NUMBER_COLOR, new RGB(0, 0, 0)); WorkbenchChainedTextFontFieldEditor.startPropagate(store, JFaceResources.TEXT_FONT); PreferenceConverter.setDefault(store, CompilationUnitEditor.LINKED_POSITION_COLOR, new RGB(0, 200 , 100)); PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, rgbs[1]); store.setDefault(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT, true); PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, rgbs[2]); store.setDefault(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, true); store.setDefault(JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH, 4); store.setDefault(CompilationUnitEditor.SPACES_FOR_TABS, false); PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT, new RGB(63, 127, 95)); store.setDefault(IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + "_bold", false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT, new RGB(63, 127, 95)); store.setDefault(IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + "_bold", false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_KEYWORD, new RGB(127, 0, 85)); store.setDefault(IJavaColorConstants.JAVA_KEYWORD + "_bold", true); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_STRING, new RGB(42, 0, 255)); store.setDefault(IJavaColorConstants.JAVA_STRING + "_bold", false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_DEFAULT, new RGB(0, 0, 0)); store.setDefault(IJavaColorConstants.JAVA_DEFAULT + "_bold", false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_KEYWORD, new RGB(127, 159, 191)); store.setDefault(IJavaColorConstants.JAVADOC_KEYWORD + "_bold", true); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_TAG, new RGB(127, 127, 159)); store.setDefault(IJavaColorConstants.JAVADOC_TAG + "_bold", false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_LINK, new RGB(63, 63, 191)); store.setDefault(IJavaColorConstants.JAVADOC_LINK + "_bold", false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_DEFAULT, new RGB(63, 95, 191)); store.setDefault(IJavaColorConstants.JAVADOC_DEFAULT + "_bold", false); //$NON-NLS-1$ store.setDefault(ContentAssistPreference.AUTOACTIVATION, true); store.setDefault(ContentAssistPreference.AUTOACTIVATION_DELAY, 500); store.setDefault(ContentAssistPreference.AUTOINSERT, true); 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)); PreferenceConverter.setDefault(store, ContentAssistPreference.COMPLETION_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); PreferenceConverter.setDefault(store, ContentAssistPreference.COMPLETION_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$ store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$ store.setDefault(ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, true); store.setDefault(ContentAssistPreference.CASE_SENSITIVITY, false); store.setDefault(ContentAssistPreference.ORDER_PROPOSALS, false); store.setDefault(ContentAssistPreference.ADD_IMPORT, true); store.setDefault(ContentAssistPreference.INSERT_COMPLETION, true); store.setDefault(ContentAssistPreference.FILL_METHOD_ARGUMENTS, false); store.setDefault(ContentAssistPreference.GUESS_METHOD_ARGUMENTS, true); store.setDefault(CompilationUnitEditor.CLOSE_STRINGS, true); store.setDefault(CompilationUnitEditor.CLOSE_BRACKETS, true); store.setDefault(CompilationUnitEditor.CLOSE_JAVADOCS, true); store.setDefault(CompilationUnitEditor.WRAP_STRINGS, true); store.setDefault(CompilationUnitEditor.ADD_JAVADOC_TAGS, true); store.setDefault(CompilationUnitEditor.FORMAT_JAVADOCS, true); store.setDefault(AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END, true); } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); } private void handleSyntaxColorListSelection() { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fSyntaxForegroundColorEditor.setColorValue(rgb); fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); } private void handleAppearanceColorListSelection() { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAppearanceForegroundColorEditor.setColorValue(rgb); } private void handleProblemIndicationColorListSelection() { int i= fProblemIndicationColorList.getSelectionIndex(); String key= fProblemIndicationColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fProblemIndicationForegroundColorEditor.setColorValue(rgb); } private Control createSyntaxPage(Composite parent) { Composite colorComposite= new Composite(parent, SWT.NULL); colorComposite.setLayout(new GridLayout()); Group backgroundComposite= new Group(colorComposite, SWT.SHADOW_ETCHED_IN); backgroundComposite.setLayout(new RowLayout()); backgroundComposite.setText(JavaUIMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ SelectionListener backgroundSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean custom= fBackgroundCustomRadioButton.getSelection(); fBackgroundColorButton.setEnabled(custom); fOverlayStore.setValue(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, !custom); } public void widgetDefaultSelected(SelectionEvent e) {} }; fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundDefaultRadioButton.setText(JavaUIMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundCustomRadioButton.setText(JavaUIMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundColorEditor= new ColorEditor(backgroundComposite); fBackgroundColorButton= fBackgroundColorEditor.getButton(); Label label= new Label(colorComposite, SWT.LEFT); label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite editorComposite= new Composite(colorComposite, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); editorComposite.setLayoutData(gd); fSyntaxColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fSyntaxColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); label= new Label(stylesComposite, SWT.LEFT); label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fSyntaxForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fBoldCheckBox= new Button(stylesComposite, SWT.CHECK); fBoldCheckBox.setText(JavaUIMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fBoldCheckBox.setLayoutData(gd); label= new Label(colorComposite, SWT.LEFT); label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control previewer= createPreviewer(colorComposite); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(20); gd.heightHint= convertHeightInCharsToPixels(5); previewer.setLayoutData(gd); fSyntaxColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleSyntaxColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fSyntaxForegroundColorEditor.getColorValue()); } }); fBackgroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { PreferenceConverter.setValue(fOverlayStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, fBackgroundColorEditor.getColorValue()); } }); fBoldCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; fOverlayStore.setValue(key + BOLD, fBoldCheckBox.getSelection()); } }); return colorComposite; } private Control createPreviewer(Composite parent) { fJavaTextTools= new JavaTextTools(fOverlayStore); fPreviewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); fPreviewViewer.configure(new JavaSourceViewerConfiguration(fJavaTextTools, null)); fPreviewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); fPreviewViewer.setEditable(false); initializeViewerColors(fPreviewViewer); String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ IDocument document= new Document(content); IDocumentPartitioner partitioner= fJavaTextTools.createDocumentPartitioner(); partitioner.connect(document); document.setDocumentPartitioner(partitioner); fPreviewViewer.setDocument(document); fOverlayStore.addPropertyChangeListener(new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String p= event.getProperty(); if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) || p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { initializeViewerColors(fPreviewViewer); } fPreviewViewer.invalidateTextPresentation(); } }); return fPreviewViewer.getControl(); } /** * Initializes the given viewer's colors. * * @param viewer the viewer to be initialized */ private void initializeViewerColors(ISourceViewer viewer) { IPreferenceStore store= fOverlayStore; if (store != null) { StyledText styledText= viewer.getTextWidget(); // ---------- background color ---------------------- Color color= store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT) ? null : createColor(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, styledText.getDisplay()); styledText.setBackground(color); if (fBackgroundColor != null) fBackgroundColor.dispose(); fBackgroundColor= color; } } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } // sets enabled flag for a control and all its sub-tree private static void setEnabled(Control control, boolean enable) { control.setEnabled(enable); if (control instanceof Composite) { Composite composite= (Composite) control; Control[] children= composite.getChildren(); for (int i= 0; i < children.length; i++) setEnabled(children[i], enable); } } private Control createAppearancePage(Composite parent) { Composite appearanceComposite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; appearanceComposite.setLayout(layout); String label= JavaUIMessages.getString("JavaEditorPreferencePage.textFont"); //$NON-NLS-1$ addTextFontEditor(appearanceComposite, label, AbstractTextEditor.PREFERENCE_FONT); label= JavaUIMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ addTextField(appearanceComposite, label, JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH, 3, 0, true); label= JavaUIMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ addTextField(appearanceComposite, label, CompilationUnitEditor.PRINT_MARGIN_COLUMN, 3, 0, true); label= JavaUIMessages.getString("JavaEditorPreferencePage.synchronizeOnCursor"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, JavaEditorPreferencePage.PREF_SYNC_OUTLINE_ON_CURSOR_MOVE, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, CompilationUnitEditor.OVERVIEW_RULER, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, JavaEditor.LINE_NUMBER_RULER, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, CompilationUnitEditor.MATCHING_BRACKETS, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, CompilationUnitEditor.CURRENT_LINE, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, CompilationUnitEditor.PRINT_MARGIN, 0); Label l= new Label(appearanceComposite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(appearanceComposite, SWT.LEFT); l.setText(JavaUIMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(appearanceComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fAppearanceColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(JavaUIMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fAppearanceForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fAppearanceForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fAppearanceColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAppearanceColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAppearanceForegroundColorEditor.getColorValue()); } }); return appearanceComposite; } private Control createProblemIndicationPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String label= "Analyse problems while &typing"; addCheckBox(composite, label, CompilationUnitDocumentProvider.HANDLE_TEMPORARY_PROBLEMS, 0); label= "Highlight &errors in text"; addCheckBox(composite, label, CompilationUnitEditor.ERROR_INDICATION, 0); label= "Show e&rrors in overview ruler"; addCheckBox(composite, label, CompilationUnitEditor.ERROR_INDICATION_IN_OVERVIEW_RULER, 0); label= "Highlight &warnings in text"; addCheckBox(composite, label, CompilationUnitEditor.WARNING_INDICATION, 0); label= "Show warnin&gs in overview ruler"; addCheckBox(composite, label, CompilationUnitEditor.WARNING_INDICATION_IN_OVERVIEW_RULER, 0); label= "Highlight &markers in text"; addCheckBox(composite, label, CompilationUnitEditor.MARKER_INDICATION, 0); label= "Show mar&kers in overview ruler"; addCheckBox(composite, label, CompilationUnitEditor.MARKER_INDICATION_IN_OVERVIEW_RULER, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ addCheckBox(composite, label, JavaEditorPreferencePage.PREF_SHOW_TEMP_PROBLEMS, 0); Label l= new Label(composite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(composite, SWT.LEFT); l.setText("Color options for text highlighting:"); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fProblemIndicationColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fProblemIndicationColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText("Color:"); gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fProblemIndicationForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fProblemIndicationForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fProblemIndicationColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleProblemIndicationColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fProblemIndicationColorList.getSelectionIndex(); String key= fProblemIndicationColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fProblemIndicationForegroundColorEditor.getColorValue()); } }); Label note= new Label(composite, SWT.NONE); note.setText(JavaUIMessages.getString("JavaEditorPreferencePage.updatesOnNextChangeIinEditor.label")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalSpan= 2; note.setLayoutData(gd); return composite; } private Control createBehaviourPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String label= JavaUIMessages.getString("JavaEditorPreferencePage.wrapStrings"); //$NON-NLS-1$ addCheckBox(composite, label, CompilationUnitEditor.WRAP_STRINGS, 1); label= JavaUIMessages.getString("JavaEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$ addCheckBox(composite, label, AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END, 1); label= JavaUIMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$ addCheckBox(composite, label, CompilationUnitEditor.SPACES_FOR_TABS, 1); label= JavaUIMessages.getString("JavaEditorPreferencePage.closeStrings"); //$NON-NLS-1$ addCheckBox(composite, label, CompilationUnitEditor.CLOSE_STRINGS, 1); label= JavaUIMessages.getString("JavaEditorPreferencePage.closeBrackets"); //$NON-NLS-1$ addCheckBox(composite, label, CompilationUnitEditor.CLOSE_BRACKETS, 1); label= JavaUIMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); //$NON-NLS-1$ Button button= addCheckBox(composite, label, CompilationUnitEditor.CLOSE_JAVADOCS, 1); label= JavaUIMessages.getString("JavaEditorPreferencePage.addJavaDocTags"); //$NON-NLS-1$ fAddJavaDocTagsButton= addCheckBox(composite, label, CompilationUnitEditor.ADD_JAVADOC_TAGS, 1); createDependency(button, fAddJavaDocTagsButton); label= JavaUIMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); //$NON-NLS-1$ addCheckBox(composite, label, CompilationUnitEditor.FORMAT_JAVADOCS, 1); return composite; } private static void indent(Control control) { GridData gridData= new GridData(); gridData.horizontalIndent= 20; control.setLayoutData(gridData); } private static void createDependency(final Button master, final Control slave) { indent(slave); master.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) {} }); } private Control createContentAssistPage(Composite parent) { Composite contentAssistComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; contentAssistComposite.setLayout(layout); String label= JavaUIMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOINSERT, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, ContentAssistPreference.ORDER_PROPOSALS, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, ContentAssistPreference.ADD_IMPORT, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.insertCompletion"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, ContentAssistPreference.INSERT_COMPLETION, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ Button button= addCheckBox(contentAssistComposite, label, ContentAssistPreference.FILL_METHOD_ARGUMENTS, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ fGuessMethodArgumentsButton= addCheckBox(contentAssistComposite, label, ContentAssistPreference.GUESS_METHOD_ARGUMENTS, 0); createDependency(button, fGuessMethodArgumentsButton); label= JavaUIMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$ final Button autoactivation= addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$ fAutoInsertDelayText= addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_DELAY, 4, 0, true); label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$ fAutoInsertJavaTriggerText= addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, 4, 0, false); label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$ fAutoInsertJavaDocTriggerText= addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, 4, 0, false); label= JavaUIMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"); //$NON-NLS-1$ addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_BACKGROUND, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"); //$NON-NLS-1$ addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_FOREGROUND, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"); //$NON-NLS-1$ addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_BACKGROUND, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"); //$NON-NLS-1$ addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_FOREGROUND, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.backgroundForCompletionReplacement"); //$NON-NLS-1$ addColorButton(contentAssistComposite, label, ContentAssistPreference.COMPLETION_REPLACEMENT_BACKGROUND, 0); label= JavaUIMessages.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"); //$NON-NLS-1$ addColorButton(contentAssistComposite, label, ContentAssistPreference.COMPLETION_REPLACEMENT_FOREGROUND, 0); autoactivation.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { updateAutoactivationControls(); } }); 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(JavaUIMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ item.setControl(createAppearancePage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ item.setControl(createSyntaxPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.codeAssist")); //$NON-NLS-1$ item.setControl(createContentAssistPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.problemIndicationTab.title")); //$NON-NLS-1$ item.setControl(createProblemIndicationPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.behaviourTab.title")); //$NON-NLS-1$ item.setControl(createBehaviourPage(folder)); initialize(); return folder; } private void initialize() { fFontEditor.setPreferenceStore(getPreferenceStore()); fFontEditor.setPreferencePage(this); fFontEditor.load(); initializeFields(); for (int i= 0; i < fSyntaxColorListModel.length; i++) fSyntaxColorList.add(fSyntaxColorListModel[i][0]); fSyntaxColorList.getDisplay().asyncExec(new Runnable() { public void run() { fSyntaxColorList.select(0); handleSyntaxColorListSelection(); } }); for (int i= 0; i < fAppearanceColorListModel.length; i++) fAppearanceColorList.add(fAppearanceColorListModel[i][0]); fAppearanceColorList.getDisplay().asyncExec(new Runnable() { public void run() { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); } }); for (int i= 0; i < fProblemIndicationColorListModel.length; i++) fProblemIndicationColorList.add(fProblemIndicationColorListModel[i][0]); fProblemIndicationColorList.getDisplay().asyncExec(new Runnable() { public void run() { fProblemIndicationColorList.select(0); handleProblemIndicationColorListSelection(); } }); } private void initializeFields() { Iterator e= fColorButtons.keySet().iterator(); while (e.hasNext()) { ColorEditor c= (ColorEditor) e.next(); String key= (String) fColorButtons.get(c); RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); c.setColorValue(rgb); } e= fCheckBoxes.keySet().iterator(); while (e.hasNext()) { Button b= (Button) e.next(); String key= (String) fCheckBoxes.get(b); b.setSelection(fOverlayStore.getBoolean(key)); } e= fTextFields.keySet().iterator(); while (e.hasNext()) { Text t= (Text) e.next(); String key= (String) fTextFields.get(t); t.setText(fOverlayStore.getString(key)); } RGB rgb= PreferenceConverter.getColor(fOverlayStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); fBackgroundColorEditor.setColorValue(rgb); boolean default_= fOverlayStore.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); fBackgroundDefaultRadioButton.setSelection(default_); fBackgroundCustomRadioButton.setSelection(!default_); fBackgroundColorButton.setEnabled(!default_); boolean closeJavaDocs= fOverlayStore.getBoolean(CompilationUnitEditor.CLOSE_JAVADOCS); fAddJavaDocTagsButton.setEnabled(closeJavaDocs); boolean fillMethodArguments= fOverlayStore.getBoolean(ContentAssistPreference.FILL_METHOD_ARGUMENTS); fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); updateAutoactivationControls(); } private void updateAutoactivationControls() { boolean autoactivation= fOverlayStore.getBoolean(ContentAssistPreference.AUTOACTIVATION); fAutoInsertDelayText.setEnabled(autoactivation); fAutoInsertJavaTriggerText.setEnabled(autoactivation); fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); } /* * @see PreferencePage#performOk() */ public boolean performOk() { fFontEditor.store(); fOverlayStore.propagate(); JavaPlugin.getDefault().savePluginPreferences(); return true; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fFontEditor.loadDefault(); fOverlayStore.loadDefaults(); initializeFields(); handleSyntaxColorListSelection(); handleAppearanceColorListSelection(); handleProblemIndicationColorListSelection(); 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 Control addColorButton(Composite composite, String label, String key, int indentation) { Label labelControl= new Label(composite, SWT.NONE); labelControl.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; labelControl.setLayoutData(gd); ColorEditor editor= new ColorEditor(composite); Button button= editor.getButton(); button.setData(editor); gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); button.setLayoutData(gd); button.addSelectionListener(fColorButtonListener); fColorButtons.put(editor, key); return composite; } private Button addCheckBox(Composite parent, String label, String key, int indentation) { Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; gd.horizontalSpan= 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); fCheckBoxes.put(checkBox, key); return checkBox; } private Control addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { Label labelControl= new Label(composite, SWT.NONE); labelControl.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; labelControl.setLayoutData(gd); Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE); gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.widthHint= convertWidthInCharsToPixels(textLimit + 1); textControl.setLayoutData(gd); textControl.setTextLimit(textLimit); fTextFields.put(textControl, key); if (isNumber) { fNumberFields.add(textControl); textControl.addModifyListener(fNumberFieldListener); } else { textControl.addModifyListener(fTextFieldListener); } return textControl; } private void addTextFontEditor(Composite parent, String label, String key) { Composite editorComposite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 3; editorComposite.setLayout(layout); fFontEditor= new WorkbenchChainedTextFontFieldEditor(key, label, editorComposite); fFontEditor.setChangeButtonText(JavaUIMessages.getString("JavaEditorPreferencePage.change")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); 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(); } private void numberFieldChanged(Text textControl) { String number= textControl.getText(); IStatus status= validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) fOverlayStore.setValue((String) fTextFields.get(textControl), number); updateStatus(status); } private IStatus validatePositiveNumber(String number) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(JavaUIMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value < 0) status.setError(JavaUIMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } catch (NumberFormatException e) { status.setError(JavaUIMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } private void updateStatus(IStatus status) { if (!status.matches(IStatus.ERROR)) { for (int i= 0; i < fNumberFields.size(); i++) { Text text= (Text) fNumberFields.get(i); IStatus s= validatePositiveNumber(text.getText()); status= StatusUtil.getMoreSevere(s, status); } } setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } public static boolean indicateQuixFixableProblems() { return JavaPlugin.getDefault().getPreferenceStore().getBoolean(JavaEditorPreferencePage.PREF_SHOW_TEMP_PROBLEMS); } static public boolean synchronizeOutlineOnCursorMove() { return JavaPlugin.getDefault().getPreferenceStore().getBoolean(PREF_SYNC_OUTLINE_ON_CURSOR_MOVE); } }
24,890
Bug 24890 working sets: empty name inconsistencies [dialogs]
20021016 The 'New Working set' dialog allows empty names while the 'Edit' dialog does not like them
verified fixed
121bba8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-28T18:30:10Z
2002-10-17T07:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/JavaWorkingSetPage.java
25,199
Bug 25199 Do not show import declarations children on members view [browsing]
R2.0.1 In the Java Browsing Perspective, the Members View has a plus sign where you can see the import declarations. When you have many import statments and the import declaration has focus it can be annoying if trying to navigate to a method because if you "close" the import declarations (pressing the minus sign) it reopens because import has the focus and you are obliged to scroll down the view until you find the method you want. Suggestion is to keep the import declarations (very useful) but do not show its children (useless in my opinion). This way the import declarations can be viewed like a method (that is usually what I want).
verified fixed
b5ea3a7
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-28T18:45:50Z
2002-10-22T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/MembersView.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; public class MembersView extends JavaBrowsingPart implements IPropertyChangeListener { private MemberFilterActionGroup fMemberFilterActionGroup; public MembersView() { setHasWorkingSetFilter(false); setHasCustomSetFilter(false); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); } /** * Creates and returns the label provider for this part. * * @return the label provider * @see ILabelProvider */ protected ILabelProvider createLabelProvider() { return new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS, AppearanceAwareLabelProvider.getDecorators(true, new OverrideIndicatorLabelDecorator(null)) ); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ protected String getHelpContextId() { return IJavaHelpContextIds.MEMBERS_VIEW; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { ProblemTreeViewer viewer= new ProblemTreeViewer(parent, SWT.MULTI); fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaUI.ID_MEMBERS_VIEW); return viewer; } protected void fillToolBar(IToolBarManager tbm) { tbm.add(new LexicalSortingAction(getViewer(), JavaUI.ID_MEMBERS_VIEW)); fMemberFilterActionGroup.contributeToToolBar(tbm); } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ protected boolean isValidInput(Object element) { if (element instanceof IType) { IType type= (IType)element; return type.isBinary() || type.getDeclaringType() == null; } return false; } /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element instanceof IMember) return super.isValidElement(((IMember)element).getDeclaringType()); else if (element instanceof IImportDeclaration) return isValidElement(((IJavaElement)element).getParent()); else if (element instanceof IImportContainer) { Object input= getViewer().getInput(); if (input instanceof IJavaElement) { ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT); return cu.equals(importContainerCu); } else { IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE); IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE); return cf != null && cf.equals(importContainerCf); } } } return false; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ protected IJavaElement findElementToSelect(IJavaElement je) { if (je == null) return null; switch (je.getElementType()) { case IJavaElement.TYPE: if (((IType)je).getDeclaringType() == null) return null; // fall through case IJavaElement.METHOD: // fall through case IJavaElement.FIELD: // fall through case IJavaElement.PACKAGE_DECLARATION: // fall through case IJavaElement.IMPORT_CONTAINER: return getSuitableJavaElement(je); case IJavaElement.IMPORT_DECLARATION: je= getSuitableJavaElement(je); if (je != null) { ICompilationUnit cu= (ICompilationUnit)je.getParent().getParent(); try { if (cu.getImports()[0].equals(je)) { Object selectedElement= getSingleElementFromSelection(getViewer().getSelection()); if (selectedElement instanceof IImportContainer) return (IImportContainer)selectedElement; } } catch (JavaModelException ex) { // return je; } return je; } break; } return null; } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; switch (je.getElementType()) { case IJavaElement.TYPE: IType type= ((IType)je).getDeclaringType(); if (type == null) return je; else return findInputForJavaElement(type); case IJavaElement.COMPILATION_UNIT: return getTypeForCU((ICompilationUnit)je); case IJavaElement.CLASS_FILE: try { return findInputForJavaElement(((IClassFile)je).getType()); } catch (JavaModelException ex) { return null; } case IJavaElement.IMPORT_DECLARATION: return findInputForJavaElement(je.getParent()); case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: IJavaElement parent= je.getParent(); if (parent instanceof ICompilationUnit) { IType[] types; try { types= ((ICompilationUnit)parent).getAllTypes(); } catch (JavaModelException ex) { return null; } if (types.length > 0) return types[0]; else return null; } else if (parent instanceof IClassFile) return findInputForJavaElement(parent); default: if (je instanceof IMember) return findInputForJavaElement(((IMember)je).getDeclaringType()); } return null; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { super.saveState(memento); fMemberFilterActionGroup.saveState(memento); } protected void restoreState(IMemento memento) { super.restoreState(memento); fMemberFilterActionGroup.restoreState(memento); getViewer().getControl().setRedraw(false); getViewer().refresh(); getViewer().getControl().setRedraw(true); } protected void hookViewerListeners() { super.hookViewerListeners(); getViewer().addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { TreeViewer viewer= (TreeViewer)getViewer(); Object element= ((IStructuredSelection)event.getSelection()).getFirstElement(); if (viewer.isExpandable(element)) viewer.setExpandedState(element, !viewer.getExpandedState(element)); } }); } boolean isInputAWorkingCopy() { Object input= getViewer().getInput(); if (input instanceof IJavaElement) { ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) return cu.isWorkingCopy(); } return false; } protected void restoreSelection() { IEditorPart editor= getViewSite().getPage().getActiveEditor(); if (editor != null) setSelectionFromEditor(editor); } /* (non-Javadoc) * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(MembersOrderPreferencePage.PREF_OUTLINE_SORT_OPTION)) { getViewer().refresh(); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#dispose() */ public void dispose() { super.dispose(); JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); } }
24,841
Bug 24841 Refactoring should use IWorkbench.saveAllEditors [refactoring]
null
verified fixed
d06c340
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-29T13:24:22Z
2002-10-16T14:53:20Z
org.eclipse.jdt.ui/ui
24,841
Bug 24841 Refactoring should use IWorkbench.saveAllEditors [refactoring]
null
verified fixed
d06c340
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-29T13:24:22Z
2002-10-16T14:53:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RefactoringStarter.java
20,662
Bug 20662 add .jar file to java build path from context menu in navigator [build path]
I'd like to be able to add a jar file to the current project build path from the resource navigator, via the context menu. This is a lot simpler than going through the project properties. It feels more natural to me to right click and add the library.
verified fixed
36bb3e3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-30T09:54:03Z
2002-06-19T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/IJavaHelpContextIds.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui; import org.eclipse.jdt.ui.JavaUI; /** * Help context ids for the Java UI. * <p> * This interface contains constants only; it is not intended to be implemented * or extended. * </p> * */ public interface IJavaHelpContextIds { public static final String PREFIX= JavaUI.ID_PLUGIN + '.'; // Actions public static final String GETTERSETTER_ACTION= PREFIX + "getter_setter_action_context"; //$NON-NLS-1$ public static final String ADD_METHODSTUB_ACTION= PREFIX + "add_methodstub_action_context"; //$NON-NLS-1$ public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$ public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$ public static final String SHOW_IN_PACKAGEVIEW_ACTION= PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$ public static final String SHOW_IN_HIERARCHYVIEW_ACTION= PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$ public static final String FOCUS_ON_SELECTION_ACTION= PREFIX + "focus_on_selection_action"; //$NON-NLS-1$ public static final String FOCUS_ON_TYPE_ACTION= PREFIX + "focus_on_type_action"; //$NON-NLS-1$ public static final String TYPEHIERARCHY_HISTORY_ACTION= PREFIX + "typehierarchy_history_action"; //$NON-NLS-1$ public static final String FILTER_PUBLIC_ACTION= PREFIX + "filter_public_action"; //$NON-NLS-1$ public static final String FILTER_FIELDS_ACTION= PREFIX + "filter_fields_action"; //$NON-NLS-1$ public static final String FILTER_STATIC_ACTION= PREFIX + "filter_static_action"; //$NON-NLS-1$ public static final String SHOW_INHERITED_ACTION= PREFIX + "show_inherited_action"; //$NON-NLS-1$ public static final String SHOW_SUPERTYPES= PREFIX + "show_supertypes_action"; //$NON-NLS-1$ public static final String SHOW_SUBTYPES= PREFIX + "show_subtypes_action"; //$NON-NLS-1$ public static final String SHOW_HIERARCHY= PREFIX + "show_hierarchy_action"; //$NON-NLS-1$ public static final String ENABLE_METHODFILTER_ACTION= PREFIX + "enable_methodfilter_action"; //$NON-NLS-1$ public static final String ADD_IMPORT_ON_SELECTION_ACTION= PREFIX + "add_imports_on_selection_action_context"; //$NON-NLS-1$ public static final String ORGANIZE_IMPORTS_ACTION= PREFIX + "organize_imports_action_context"; //$NON-NLS-1$ public static final String TOGGLE_PRESENTATION_ACTION= PREFIX + "toggle_presentation_action_context"; //$NON-NLS-1$ public static final String TOGGLE_TEXTHOVER_ACTION= PREFIX + "toggle_texthover_action_context"; //$NON-NLS-1$ public static final String OPEN_CLASS_WIZARD_ACTION= PREFIX + "open_class_wizard_action"; //$NON-NLS-1$ public static final String OPEN_INTERFACE_WIZARD_ACTION= PREFIX + "open_interface_wizard_action"; //$NON-NLS-1$ public static final String OPEN_PACKAGE_WIZARD_ACTION= PREFIX + "open_package_wizard_action"; //$NON-NLS-1$ public static final String OPEN_PROJECT_WIZARD_ACTION= PREFIX + "open_project_wizard_action"; //$NON-NLS-1$ public static final String OPEN_SNIPPET_WIZARD_ACTION= PREFIX + "open_snippet_wizard_action"; //$NON-NLS-1$ public static final String EDIT_WORKING_SET_ACTION= PREFIX + "edit_working_set_action"; //$NON-NLS-1$ public static final String CLEAR_WORKING_SET_ACTION= PREFIX + "clear_working_set_action"; //$NON-NLS-1$ public static final String GOTO_MARKER_ACTION= PREFIX + "goto_marker_action"; //$NON-NLS-1$ public static final String GOTO_PACKAGE_ACTION= PREFIX + "goto_package_action"; //$NON-NLS-1$ public static final String HISTORY_ACTION= PREFIX + "history_action"; //$NON-NLS-1$ public static final String HISTORY_LIST_ACTION= PREFIX + "history_list_action"; //$NON-NLS-1$ public static final String LEXICAL_SORTING_OUTLINE_ACTION= PREFIX + "lexical_sorting_outline_action"; //$NON-NLS-1$ public static final String LEXICAL_SORTING_BROWSING_ACTION= PREFIX + "lexical_sorting_browsing_action"; //$NON-NLS-1$ public static final String OPEN_JAVA_PERSPECTIVE_ACTION= PREFIX + "open_java_perspective_action"; //$NON-NLS-1$ public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION= PREFIX + "open_java_browsing_perspective_action"; //$NON-NLS-1$ public static final String OPEN_PROJECT_ACTION= PREFIX + "open_project_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_ACTION= PREFIX + "open_type_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_IN_HIERARCHY_ACTION= PREFIX + "open_type_in_hierarchy_action"; //$NON-NLS-1$ public static final String ADD_JAVADOC_STUB_ACTION= PREFIX + "add_javadoc_stub_action"; //$NON-NLS-1$ public static final String ADD_TASK_ACTION= PREFIX + "add_task_action"; //$NON-NLS-1$ public static final String EXTERNALIZE_STRINGS_ACTION= PREFIX + "externalize_strings_action"; //$NON-NLS-1$ public static final String EXTRACT_METHOD_ACTION= PREFIX + "extract_method_action"; //$NON-NLS-1$ public static final String EXTRACT_TEMP_ACTION= PREFIX + "extract_temp_action"; //$NON-NLS-1$ public static final String PROMOTE_TEMP_TO_FIELD_ACTION= PREFIX + "promote_temp_to_field_action"; //$NON-NLS-1$ public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION= PREFIX + "convert_anonymous_to_nested_action"; //$NON-NLS-1$ public static final String EXTRACT_CONSTANT_ACTION= PREFIX + "extract_constant_action"; //$NON-NLS-1$ public static final String EXTRACT_INTERFACE_ACTION= PREFIX + "extract_interface_action"; //$NON-NLS-1$ public static final String MOVE_INNER_TO_TOP_ACTION= PREFIX + "move_inner_to_top_level_action"; //$NON-NLS-1$ public static final String USE_SUPERTYPE_ACTION= PREFIX + "use_supertype_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION= PREFIX + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION= PREFIX + "find_declarations_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION= PREFIX + "find_implementors_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_ACTION= PREFIX + "find_read_references_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_read_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_write_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_ACTION= PREFIX + "find_write_references_action"; //$NON-NLS-1$ public static final String WORKING_SET_FIND_ACTION= PREFIX + "working_set_find_action"; //$NON-NLS-1$ public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION= PREFIX + "find_strings_to_externalize_action"; //$NON-NLS-1$ public static final String INLINE_TEMP_ACTION= PREFIX + "inline_temp_action"; //$NON-NLS-1$ public static final String MODIFY_PARAMETERS_ACTION= PREFIX + "modify_parameters_action"; //$NON-NLS-1$ public static final String MOVE_ACTION= PREFIX + "move_action"; //$NON-NLS-1$ public static final String OPEN_ACTION= PREFIX + "open_action"; //$NON-NLS-1$ public static final String OPEN_EXTERNAL_JAVADOC_ACTION= PREFIX + "open_external_javadoc_action"; //$NON-NLS-1$ public static final String OPEN_SUPER_IMPLEMENTATION_ACTION= PREFIX + "open_super_implementation_action"; //$NON-NLS-1$ public static final String PULL_UP_ACTION= PREFIX + "pull_up_action"; //$NON-NLS-1$ public static final String REFRESH_ACTION= PREFIX + "refresh_action"; //$NON-NLS-1$ public static final String RENAME_ACTION= PREFIX + "rename_action"; //$NON-NLS-1$ public static final String SELF_ENCAPSULATE_ACTION= PREFIX + "self_encapsulate_action"; //$NON-NLS-1$ public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION= PREFIX + "show_in_navigator_action"; //$NON-NLS-1$ public static final String SURROUND_WITH_TRY_CATCH_ACTION= PREFIX + "surround_with_try_catch_action"; //$NON-NLS-1$ public static final String OPEN_RESOURCE_ACTION= PREFIX + "open_resource_action"; //$NON-NLS-1$ public static final String SELECT_WORKING_SET_ACTION= PREFIX + "select_working_set_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECTION_HISTORY_ACTION= PREFIX + "structured_selection_history_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_ENCLOSING_ACTION= PREFIX + "structured_select_enclosing_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_NEXT_ACTION= PREFIX + "structured_select_next_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_PREVIOUS_ACTION= PREFIX + "structured_select_previous_action"; //$NON-NLS-1$ public static final String TOGGLE_ORIENTATION_ACTION= PREFIX + "toggle_orientations_action"; //$NON-NLS-1$ public static final String CUT_ACTION= PREFIX + "cut_action"; //$NON-NLS-1$ public static final String COPY_ACTION= PREFIX + "copy_action"; //$NON-NLS-1$ public static final String PASTE_ACTION= PREFIX + "paste_action"; //$NON-NLS-1$ public static final String DELETE_ACTION= PREFIX + "delete_action"; //$NON-NLS-1$ public static final String SELECT_ALL_ACTION= PREFIX + "select_all_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_HIERARCHY_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ public static final String COLLAPSE_ALL_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ // Dialogs public static final String MAINTYPE_SELECTION_DIALOG= PREFIX + "maintype_selection_dialog_context"; //$NON-NLS-1$ public static final String OPEN_TYPE_DIALOG= PREFIX + "open_type_dialog_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_DIALOG= PREFIX + "source_attachment_dialog_context"; //$NON-NLS-1$ public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG= PREFIX + "advanced_dialog_context"; //$NON-NLS-1$ public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG= PREFIX + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$ public static final String NEW_VARIABLE_ENTRY_DIALOG= PREFIX + "new_variable_dialog_context"; //$NON-NLS-1$ public static final String COMPARE_DIALOG= PREFIX + "compare_dialog_context"; //$NON-NLS-1$ public static final String NONNLS_DIALOG= PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$ public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG= PREFIX + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$ public static final String MULTI_TYPE_SELECTION_DIALOG= PREFIX + "multi_type_selection_dialog_context"; //$NON-NLS-1$ public static final String SUPER_INTERFACE_SELECTION_DIALOG= PREFIX + "super_interface_selection_dialog_context"; //$NON-NLS-1$ public static final String OVERRIDE_TREE_SELECTION_DIALOG= PREFIX + "override_tree_selection_dialog_context"; //$NON-NLS-1$ public static final String MOVE_DESTINATION_DIALOG= PREFIX + "move_destination_dialog_context"; //$NON-NLS-1$ public static final String CHOOSE_VARIABLE_DIALOG= PREFIX + "choose_variable_dialog_context"; //$NON-NLS-1$ public static final String EDIT_TEMPLATE_DIALOG= PREFIX + "edit_template_dialog_context"; //$NON-NLS-1$ public static final String HISTORY_LIST_DIALOG= PREFIX + "history_list_dialog_context"; //$NON-NLS-1$ public static final String IMPORT_ORGANIZE_INPUT_DIALOG= PREFIX + "import_organize_input_dialog_context"; //$NON-NLS-1$ public static final String JAVADOC_PROPERTY_DIALOG= PREFIX + "javadoc_property_dialog_context"; //$NON-NLS-1$ public static final String NEW_CONTAINER_DIALOG= PREFIX + "new_container_dialog_context"; //$NON-NLS-1$ public static final String VARIABLE_CREATION_DIALOG= PREFIX + "variable_creation_dialog_context"; //$NON-NLS-1$ public static final String JAVA_SEARCH_PAGE= PREFIX + "java_search_page_context"; //$NON-NLS-1$ public static final String NLS_SEARCH_PAGE= PREFIX + "nls_search_page_context"; //$NON-NLS-1$ public static final String JAVA_EDITOR= PREFIX + "java_editor_context"; //$NON-NLS-1$ // view parts public static final String TYPE_HIERARCHY_VIEW= PREFIX + "type_hierarchy_view_context"; //$NON-NLS-1$ public static final String PACKAGES_VIEW= PREFIX + "package_view_context"; //$NON-NLS-1$ public static final String PROJECTS_VIEW= PREFIX + "projects_view_context"; //$NON-NLS-1$ public static final String PACKAGES_BROWSING_VIEW= PREFIX + "packages_browsing_view_context"; //$NON-NLS-1$ public static final String TYPES_VIEW= PREFIX + "types_view_context"; //$NON-NLS-1$ public static final String MEMBERS_VIEW= PREFIX + "members_view_context"; //$NON-NLS-1$ // Preference/Property pages public static final String APPEARANCE_PREFERENCE_PAGE= PREFIX + "appearance_preference_page_context"; //$NON-NLS-1$ public static final String SORT_ORDER_PREFERENCE_PAGE= PREFIX + "sort_order_preference_page_context"; //$NON-NLS-1$ public static final String BUILD_PATH_PROPERTY_PAGE= PREFIX + "build_path_property_page_context"; //$NON-NLS-1$ public static final String CP_VARIABLES_PREFERENCE_PAGE= PREFIX + "cp_variables_preference_page_context"; //$NON-NLS-1$ public static final String CODEFORMATTER_PREFERENCE_PAGE= PREFIX + "codeformatter_preference_page_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE= PREFIX + "source_attachment_property_page_context"; //$NON-NLS-1$ public static final String CODE_MANIPULATION_PREFERENCE_PAGE= PREFIX + "code_manipulation_preference_context"; //$NON-NLS-1$ public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE= PREFIX + "organizeimports_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_BASE_PREFERENCE_PAGE= PREFIX + "java_base_preference_page_context"; //$NON-NLS-1$ public static final String REFACTORING_PREFERENCE_PAGE= PREFIX + "refactoring_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_EDITOR_PREFERENCE_PAGE= PREFIX + "java_editor_preference_page_context"; //$NON-NLS-1$ public static final String COMPILER_PREFERENCE_PAGE= PREFIX + "compiler_preference_page_context"; //$NON-NLS-1$ public static final String TEMPLATE_PREFERENCE_PAGE= PREFIX + "template_preference_page_context"; //$NON-NLS-1$ public static final String JAVADOC_PREFERENCE_PAGE= PREFIX + "javadoc_preference_page_context"; //$NON-NLS-1$ public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_ELEMENT_INFO_PAGE= PREFIX + "java_element_info_page_context"; //$NON-NLS-1$ // Wizard pages public static final String NEW_JAVAPROJECT_WIZARD_PAGE= PREFIX + "new_javaproject_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_SNIPPET_WIZARD_PAGE= PREFIX + "new_snippet_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_PACKAGE_WIZARD_PAGE= PREFIX + "new_package_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_CLASS_WIZARD_PAGE= PREFIX + "new_class_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_INTERFACE_WIZARD_PAGE= PREFIX + "new_interface_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_PACKAGEROOT_WIZARD_PAGE= PREFIX + "new_packageroot_wizard_page_context"; //$NON-NLS-1$ public static final String JARPACKAGER_WIZARD_PAGE= PREFIX + "jar_packager_wizard_page_context"; //$NON-NLS-1$ public static final String JARMANIFEST_WIZARD_PAGE= PREFIX + "jar_manifest_wizard_page_context"; //$NON-NLS-1$ public static final String JAROPTIONS_WIZARD_PAGE= PREFIX + "jar_options_wizard_page_context"; //$NON-NLS-1$ public static final String JAVA_WORKING_SET_PAGE= PREFIX + "java_working_set_page_context"; //$NON-NLS-1$ public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE= PREFIX + "classpath_container_default_page_context"; //$NON-NLS-1$ public static final String JAVADOC_STANDARD_PAGE= PREFIX + "javadoc_standard_page_context"; //$NON-NLS-1$ public static final String JAVADOC_SPECIFICS_PAGE= PREFIX + "javadoc_specifics_page_context"; //$NON-NLS-1$ public static final String JAVADOC_TREE_PAGE= PREFIX + "javadoc_tree_page_context"; //$NON-NLS-1$ // same help for all refactoring preview pages public static final String REFACTORING_PREVIEW_WIZARD_PAGE= PREFIX + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_CU_ERROR_WIZARD_PAGE= PREFIX + "move_cu_error_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_PARAMS_WIZARD_PAGE= PREFIX + "rename_params_wizard_page"; //$NON-NLS-1$ public static final String RENAME_PARAMS_ERROR_WIZARD_PAGE= PREFIX + "rename_params_error_wizard_page"; //$NON-NLS-1$ public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE= PREFIX + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$ public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE= PREFIX + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$ public static final String EXTERNALIZE_ERROR_WIZARD_PAGE= PREFIX + "externalize_error_wizard_page_context"; //$NON-NLS-1$ public static final String EXTRACT_INTERFACE_WIZARD_PAGE= PREFIX + "extract_interface_temp_page_context"; //$NON-NLS-1$ public static final String EXTRACT_INTERFACE_ERROR_WIZARD_PAGE= PREFIX + "extract_interface_error_wizard_page_context"; //$NON-NLS-1$ public static final String EXTRACT_METHOD_WIZARD_PAGE= PREFIX + "extract_method_wizard_page_context"; //$NON-NLS-1$ public static final String EXTRACT_METHOD_ERROR_WIZARD_PAGE= PREFIX + "extract_method_error_wizard_page_context"; //$NON-NLS-1$ public static final String EXTRACT_TEMP_WIZARD_PAGE= PREFIX + "extract_temp_page_context"; //$NON-NLS-1$ public static final String EXTRACT_TEMP_ERROR_WIZARD_PAGE= PREFIX + "extract_temp_error_wizard_page_context"; //$NON-NLS-1$ public static final String EXTRACT_CONSTANT_WIZARD_PAGE= PREFIX + "extract_constant_page_context"; //$NON-NLS-1$ public static final String EXTRACT_CONSTANT_ERROR_WIZARD_PAGE= PREFIX + "extract_constant_error_wizard_page_context"; //$NON-NLS-1$ public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE= PREFIX + "promote_temp_to_field_page_context"; //$NON-NLS-1$ public static final String PROMOTE_TEMP_TO_FIELD_ERROR_WIZARD_PAGE= PREFIX + "promote_temp_to_field_error_wizard_page_context"; //$NON-NLS-1$ public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$ public static final String CONVERT_ANONYMOUS_TO_NESTED_ERROR_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_error_wizard_page_context"; //$NON-NLS-1$ public static final String MODIFY_PARAMETERS_WIZARD_PAGE= PREFIX + "modify_parameters_wizard_page_context"; //$NON-NLS-1$ public static final String MODIFY_PARAMETERS_ERROR_WIZARD_PAGE= PREFIX + "modify_parameters_error_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_MEMBERS_WIZARD_PAGE= PREFIX + "move_members_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_MEMBERS_ERROR_WIZARD_PAGE= PREFIX + "move_members_error_error_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE= PREFIX + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_INNER_TO_TOP_ERROR_WIZARD_PAGE= PREFIX + "move_inner_to_top_error_error_wizard_page_context"; //$NON-NLS-1$ public static final String PULL_UP_WIZARD_PAGE= PREFIX + "pull_up_wizard_page_context"; //$NON-NLS-1$ public static final String PULL_UP_ERROR_WIZARD_PAGE= PREFIX + "pull_up_error_error_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_PACKAGE_WIZARD_PAGE= PREFIX + "rename_package_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_PACKAGE_ERROR_WIZARD_PAGE= PREFIX + "rename_package_error_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TEMP_WIZARD_PAGE= PREFIX + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TEMP_ERROR_WIZARD_PAGE= PREFIX + "rename_local_variable_error_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_CU_WIZARD_PAGE= PREFIX + "rename_cu_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_CU_ERROR_WIZARD_PAGE= PREFIX + "rename_cu_error_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_METHOD_WIZARD_PAGE= PREFIX + "rename_method_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_METHOD_ERROR_WIZARD_PAGE= PREFIX + "rename_method_error_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TYPE_WIZARD_PAGE= PREFIX + "rename_type_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TYPE_ERROR_WIZARD_PAGE= PREFIX + "rename_type_error_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_FIELD_WIZARD_PAGE= PREFIX + "rename_field_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_FIELD_ERROR_WIZARD_PAGE= PREFIX + "rename_field_error_wizard_page_context"; //$NON-NLS-1$ public static final String SEF_WIZARD_PAGE= PREFIX + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$ public static final String SEF_ERROR_WIZARD_PAGE= PREFIX + "self_encapsulate_field_error_wizard_page_context"; //$NON-NLS-1$ public static final String USE_SUPERTYPE_WIZARD_PAGE= PREFIX + "use_supertype_wizard_page_context"; //$NON-NLS-1$ public static final String USE_SUPERTYPE_ERROR_WIZARD_PAGE= PREFIX + "use_supertype_error_wizard_page_context"; //$NON-NLS-1$ public static final String INLINE_METHOD_WIZARD_PAGE= PREFIX + "inline_method_wizard_page_context"; //$NON-NLS-1$ public static final String INLINE_METHOD_ERROR_WIZARD_PAGE= PREFIX + "inline_method_error_wizard_page_context"; //$NON-NLS-1$ // reused ui-blocks public static final String BUILD_PATH_BLOCK= PREFIX + "build_paths_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_BLOCK= PREFIX + "source_attachment_context"; //$NON-NLS-1$ // Custom Filters public static final String CUSTOM_FILTERS_DIALOG= PREFIX + "open_custom_filters_dialog_context"; //$NON-NLS-1$ }
20,662
Bug 20662 add .jar file to java build path from context menu in navigator [build path]
I'd like to be able to add a jar file to the current project build path from the resource navigator, via the context menu. This is a lot simpler than going through the project properties. It feels more natural to me to right click and add the library.
verified fixed
36bb3e3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-30T09:54:03Z
2002-06-19T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddJARToClasspathAction.java
20,662
Bug 20662 add .jar file to java build path from context menu in navigator [build path]
I'd like to be able to add a jar file to the current project build path from the resource navigator, via the context menu. This is a lot simpler than going through the project properties. It feels more natural to me to right click and add the library.
verified fixed
36bb3e3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-30T09:54:03Z
2002-06-19T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateActionGroup.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.util.Assert; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.ConvertLineDelimitersAction; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.AddBookmarkAction; import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.AddTaskAction; import org.eclipse.jdt.ui.IContextMenuConstants; /** * Action group that adds the source and generate actions to a part's context * menu and installs handlers for the corresponding global menu actions. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class GenerateActionGroup extends ActionGroup { private CompilationUnitEditor fEditor; private IWorkbenchSite fSite; private String fGroupName= IContextMenuConstants.GROUP_SOURCE; private List fRegisteredSelectionListeners; private AddImportOnSelectionAction fAddImport; private OverrideMethodsAction fOverrideMethods; private AddGetterSetterAction fAddGetterSetter; private AddUnimplementedConstructorsAction fAddUnimplementedConstructors; private AddJavaDocStubAction fAddJavaDocStub; private AddBookmarkAction fAddBookmark; private AddTaskAction fAddTaskAction; private ExternalizeStringsAction fExternalizeStrings; private FindStringsToExternalizeAction fFindStringsToExternalize; private SurroundWithTryCatchAction fSurroundWithTryCatch; private OrganizeImportsAction fOrganizeImports; private ConvertLineDelimitersAction fConvertToWindows; private ConvertLineDelimitersAction fConvertToUNIX; private ConvertLineDelimitersAction fConvertToMac; /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public GenerateActionGroup(CompilationUnitEditor editor, String groupName) { fSite= editor.getSite(); fEditor= editor; fGroupName= groupName; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fAddImport= new AddImportOnSelectionAction(editor); fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT); fAddImport.update(); editor.setAction("AddImport", fAddImport); //$NON-NLS-1$ fOrganizeImports= new OrganizeImportsAction(editor); fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS); fOrganizeImports.editorStateChanged(); editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$ fOverrideMethods= new OverrideMethodsAction(editor); fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS); fOverrideMethods.editorStateChanged(); editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$ fAddGetterSetter= new AddGetterSetterAction(editor); fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER); fAddGetterSetter.editorStateChanged(); editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$ fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor); fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS); fAddUnimplementedConstructors.editorStateChanged(); editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$ fAddJavaDocStub= new AddJavaDocStubAction(editor); fAddJavaDocStub.editorStateChanged(); fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor); fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH); fSurroundWithTryCatch.update(selection); provider.addSelectionChangedListener(fSurroundWithTryCatch); editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); //$NON-NLS-1$ fExternalizeStrings= new ExternalizeStringsAction(editor); fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS); fExternalizeStrings.editorStateChanged(); editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$ fConvertToWindows= new ConvertLineDelimitersAction(editor, "\r\n"); //$NON-NLS-1$ fConvertToWindows.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS); editor.setAction("ConvertLineDelimitersToWindows", fConvertToWindows); //$NON-NLS-1$ fConvertToUNIX= new ConvertLineDelimitersAction(editor, "\n"); //$NON-NLS-1$ fConvertToUNIX.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_UNIX); editor.setAction("ConvertLineDelimitersToUNIX", fConvertToUNIX); //$NON-NLS-1$ fConvertToMac= new ConvertLineDelimitersAction(editor, "\r"); //$NON-NLS-1$ fConvertToMac.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_MAC); editor.setAction("ConvertLineDelimitersToMac", fConvertToMac); //$NON-NLS-1$ } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the page's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param page the page that owns this action group */ public GenerateActionGroup(Page page) { this(page.getSite()); } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the part's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public GenerateActionGroup(IViewPart part) { this(part.getSite()); } private GenerateActionGroup(IWorkbenchSite site) { fSite= site; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fOverrideMethods= new OverrideMethodsAction(site); fAddGetterSetter= new AddGetterSetterAction(site); fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site); fAddJavaDocStub= new AddJavaDocStubAction(site); fAddBookmark= new AddBookmarkAction(site.getShell()); fAddTaskAction= new AddTaskAction(site); fExternalizeStrings= new ExternalizeStringsAction(site); fFindStringsToExternalize= new FindStringsToExternalizeAction(site); fOrganizeImports= new OrganizeImportsAction(site); fOverrideMethods.update(selection); fAddGetterSetter.update(selection); fAddUnimplementedConstructors.update(selection); fAddJavaDocStub.update(selection); fExternalizeStrings.update(selection); fFindStringsToExternalize.update(selection); fAddTaskAction.update(selection); fOrganizeImports.update(selection); if (selection instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection)selection; fAddBookmark.selectionChanged(ss); } else { fAddBookmark.setEnabled(false); } registerSelectionListener(provider, fOverrideMethods); registerSelectionListener(provider, fAddGetterSetter); registerSelectionListener(provider, fAddUnimplementedConstructors); registerSelectionListener(provider, fAddJavaDocStub); registerSelectionListener(provider, fAddBookmark); registerSelectionListener(provider, fExternalizeStrings); registerSelectionListener(provider, fFindStringsToExternalize); registerSelectionListener(provider, fOrganizeImports); registerSelectionListener(provider, fAddTaskAction); } private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) { if (fRegisteredSelectionListeners == null) fRegisteredSelectionListeners= new ArrayList(12); provider.addSelectionChangedListener(listener); fRegisteredSelectionListeners.add(listener); } /* * The state of the editor owning this action group has changed. * This method does nothing if the group's owner isn't an * editor. */ /** * Note: This method is for internal use only. Clients should not call this method. */ public void editorStateChanged() { Assert.isTrue(isEditorOwner()); fAddImport.update(); fExternalizeStrings.editorStateChanged(); fOrganizeImports.editorStateChanged(); fOverrideMethods.editorStateChanged(); fAddUnimplementedConstructors.editorStateChanged(); fAddJavaDocStub.editorStateChanged(); fSurroundWithTryCatch.editorStateChanged(); fAddGetterSetter.editorStateChanged(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=17709 fConvertToMac.update(); fConvertToUNIX.update(); fConvertToWindows.update(); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillActionBars(IActionBars actionBar) { super.fillActionBars(actionBar); setGlobalActionHandlers(actionBar); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); if (isEditorOwner()) { IMenuManager subMenu= createEditorSubMenu(menu); if (subMenu != null) menu.appendToGroup(fGroupName, subMenu); } else { appendToGroup(menu, fOrganizeImports); appendToGroup(menu, fOverrideMethods); appendToGroup(menu, fAddGetterSetter); appendToGroup(menu, fAddUnimplementedConstructors); appendToGroup(menu, fAddJavaDocStub); appendToGroup(menu, fAddBookmark); } } private IMenuManager createEditorSubMenu(IMenuManager mainMenu) { IMenuManager result= new MenuManager(ActionMessages.getString("SourceMenu.label")); //$NON-NLS-1$ int added= 0; added+= addEditorAction(result, "Comment"); //$NON-NLS-1$ added+= addEditorAction(result, "Uncomment"); //$NON-NLS-1$ result.add(new Separator()); added+= addAction(result, fOrganizeImports); added+= addAction(result, fAddImport); result.add(new Separator()); added+= addAction(result, fOverrideMethods); added+= addAction(result, fAddGetterSetter); added+= addAction(result, fAddUnimplementedConstructors); added+= addAction(result, fAddJavaDocStub); added+= addAction(result, fAddBookmark); result.add(new Separator()); added+= addAction(result, fSurroundWithTryCatch); added+= addAction(result, fExternalizeStrings); if (added == 0) result= null; return result; } /* (non-Javadoc) * Method declared in ActionGroup */ public void dispose() { if (fRegisteredSelectionListeners != null) { ISelectionProvider provider= fSite.getSelectionProvider(); for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) { ISelectionChangedListener listener= (ISelectionChangedListener) iter.next(); provider.removeSelectionChangedListener(listener); } } fEditor= null; super.dispose(); } private void setGlobalActionHandlers(IActionBars actionBar) { actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport); actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatch); actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub); actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings); actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize); actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_WINDOWS, fConvertToWindows); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_UNIX, fConvertToUNIX); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_MAC, fConvertToMac); if (!isEditorOwner()) { // editor provides its own implementation of these actions. actionBar.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmark); actionBar.setGlobalActionHandler(IWorkbenchActionConstants.ADD_TASK, fAddTaskAction); } } private int appendToGroup(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.appendToGroup(fGroupName, action); return 1; } return 0; } private int addAction(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.add(action); return 1; } return 0; } private int addEditorAction(IMenuManager menu, String actionID) { if (fEditor == null) return 0; IAction action= fEditor.getAction(actionID); if (action == null) return 0; if (action instanceof IUpdate) ((IUpdate)action).update(); if (action.isEnabled()) { menu.add(action); return 1; } return 0; } private boolean isEditorOwner() { return fEditor != null; } }
22,499
Bug 22499 Code assist mangles/truncates import statements [code manipulation]
I used code assist to insert an anonymous inner class, which caused SelectionChangeEvent and ISelecitonChangeListener to get aded as imports. My list of imports became truncated at approximately 3180 characters. Before the new imports were added, the import statements also totalled 3180 characters. The result is that the last 1 1/2 imports were lost, and the CU no longer compiled.
verified fixed
94a248e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-30T15:15:24Z
2002-08-16T15:00:00Z
org.eclipse.jdt.ui/core
22,499
Bug 22499 Code assist mangles/truncates import statements [code manipulation]
I used code assist to insert an anonymous inner class, which caused SelectionChangeEvent and ISelecitonChangeListener to get aded as imports. My list of imports became truncated at approximately 3180 characters. Before the new imports were added, the import statements also totalled 3180 characters. The result is that the last 1 1/2 imports were lost, and the CU no longer compiled.
verified fixed
94a248e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-30T15:15:24Z
2002-08-16T15:00:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java
25,246
Bug 25246 filecomment template does not accept '//' comments [wizards]
null
verified fixed
a4e94d2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-30T15:34:13Z
2002-10-23T13:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /** * The class <code>NewTypeWizardPage</code> contains controls and validation routines * for a 'New Type WizardPage'. Implementors decide which components to add and to enable. * Implementors can also customize the validation code. <code>NewTypeWizardPage</code> * is intended to serve as base class of all wizards that create types like applets, servlets, classes, * interfaces, etc. * <p> * See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an * example usage of <code>NewTypeWizardPage</code>. * </p> * * @see org.eclipse.jdt.ui.wizards.NewClassWizardPage * @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage * * @since 2.0 */ public abstract class NewTypeWizardPage extends NewContainerWizardPage { /** * Class used in stub creation routines to add needed imports to a * compilation unit. */ public static class ImportsManager { private IImportsStructure fImportsStructure; /* package */ ImportsManager(IImportsStructure structure) { fImportsStructure= structure; } /* package */ IImportsStructure getImportsStructure() { return fImportsStructure; } /** * Adds a new import declaration that is sorted in the existing imports. * If an import already exists or the import would conflict with another import * of an other type with the same simple name the import is not added. * * @param qualifiedTypeName The fully qualified name of the type to import * (dot separated) * @return Returns the simple type name that can be used in the code or the * fully qualified type name if an import conflict prevented the import */ public String addImport(String qualifiedTypeName) { return fImportsStructure.addImport(qualifiedTypeName); } } /** Public access flag. See The Java Virtual Machine Specification for more details. */ public int F_PUBLIC = Flags.AccPublic; /** Private access flag. See The Java Virtual Machine Specification for more details. */ public int F_PRIVATE = Flags.AccPrivate; /** Protected access flag. See The Java Virtual Machine Specification for more details. */ public int F_PROTECTED = Flags.AccProtected; /** Static access flag. See The Java Virtual Machine Specification for more details. */ public int F_STATIC = Flags.AccStatic; /** Final access flag. See The Java Virtual Machine Specification for more details. */ public int F_FINAL = Flags.AccFinal; /** Abstract property flag. See The Java Virtual Machine Specification for more details. */ public int F_ABSTRACT = Flags.AccAbstract; private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$ /** Field ID of the package input field */ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ /** Field ID of the eclosing type input field */ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ /** Field ID of the enclosing type checkbox */ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ /** Field ID of the type name input field */ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ /** Field ID of the super type input field */ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ /** Field ID of the super interfaces input field */ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ /** Field ID of the modifier checkboxes */ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ /** Field ID of the method stubs checkboxes */ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; /** * Creates a new <code>NewTypeWizardPage</code> * * @param isClass <code>true</code> if a new class is to be created; otherwise * an interface is to be created * @param pageName the wizard page's name */ public NewTypeWizardPage(boolean isClass, String pageName) { super(pageName); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the page with a given selection. * * @param elem the selection used to intialize this page or <code> * null</code> if no selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= cu.findPrimaryType(); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); } /** * Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { // #6891 Composite tabGroup= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; tabGroup.setLayout(layout); fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= getMaxFieldWidth(); gd.horizontalSpan= 2; c.setLayoutData(gd); Button button= fEnclosingTypeDialogField.getChangeControl(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); } /** * Creates the controls for the type name field. Expects a <code>GridLayout</code> with at * least 2 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the modifiers radio/ceckbox buttons. Expects a * <code>GridLayout</code> with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); Control control= fAccMdfButtons.getSelectionButtonsGroup(composite); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); control= fOtherMdfButtons.getSelectionButtonsGroup(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> * with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with * at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; gd.widthHint= getMaxFieldWidth(); } /** * Sets the focus on the type name input field. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(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 ---------------- /* * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Returns the text of the package input field. * * @return the text of the package input field */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Returns the text of the enclosing type input field. * * @return the text of the enclosing type input field */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * * @return a package fragement or <code>null</code> if the input * could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment to the given value. The method updates the model * and the text of the control. * * @param pack the package fragement to be set * @param canBeModified if <code>true</code> the package fragment is * editable; otherwise it is read-only. */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the enclosing type corresponding to the current input. * * @return the enclosing type or <code>null</code> if the enclosing type is * not selected or the input could not be resolved */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the enclosing type. The method updates the underlying model * and the text of the control. * * @param type the enclosing type * @param canBeModified if <code>true</code> the enclosing type field is * editable; otherwise it is read-only. */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns the selection state of the enclosing type checkbox. * * @return the seleciton state of the enclosing type checkbox */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type checkbox's selection state. * * @param isSelected the checkbox's selection state * @param canBeModified if <code>true</code> the enclosing type checkbox is * modifiable; otherwise it is read-only. */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Returns the type name entered into the type input field. * * @return the type name */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name input field's text to the given value. Method doesn't update * the model. * * @param name the new type name * @param canBeModified if <code>true</code> the enclosing type name field is * editable; otherwise it is read-only. */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Returns the selected modifiers. * * @return the selected modifiers * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= F_PUBLIC; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= F_PRIVATE; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= F_PROTECTED; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= F_ABSTRACT; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= F_FINAL; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= F_STATIC; } return mdf; } /** * Sets the modifiers. * * @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>, * <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code> * or <code>F_STATIC</code> or, a valid combination. * @param canBeModified if <code>true</code> the modifier fields are * editable; otherwise they are read-only * @see Flags */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Returns the content of the superclass input field. * * @return the superclass name */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * * @param name the new superclass name * @param canBeModified if <code>true</code> the superclass name field is * editable; otherwise it is read-only. */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Returns the chosen super interfaces. * * @return a list of chosen super interfaces. The list's elements * are of type <code>String</code> */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * * @param interfacesNames a list of super interface. The method requires that * the list's elements are of type <code>String</code> * @param canBeModified if <code>true</code> the super interface field is * editable; otherwise it is read-only. */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * A hook method that gets called when the package field has changed. The method * validates the package name and returns the status of the validation. The validation * also updates the package fragment model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { if (root.getJavaProject().exists() && packName.length() > 0) { try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= rootPath.append(packName.replace('.', '/')); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass } } fCurrPackage= root.getPackageFragment(packName); } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= getPackageText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Hook method that gets called when the enclosing type name has changed. The method * validates the enclosing type and returns the status of the validation. It also updates the * enclosing type model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= root.getJavaProject().findType(enclName); if (type == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type); if (!enclosingRoot.equals(root)) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$ } return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e); return status; } } /** * Hook method that gets called when the type name has changed. The method validates the * type name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Hook method that gets called when the superclass name has changed. The method * validates the superclass name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= jproject.findType(res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= jproject.findType(packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= jproject.findType(sclassName); } } return type; } /** * Hook method that gets called when the list of super interface has changed. The method * validates the superinterfaces and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= root.getJavaProject().findType(intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, checking is an extra } } } return status; } /** * Hook method that gets called when the modifiers have changed. The method validates * the modifiers and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null && froot.exists()) { packages= froot.getChildren(); } } catch (JavaModelException e) { JavaPlugin.log(e); } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); IPackageFragment pack= getPackageFragment(); if (pack != null) { dialog.setInitialSelections(new Object[] { pack }); } if (dialog.open() == ElementListSelectionDialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root }); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText())); if (dialog.open() == TypeSelectionDialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$ dialog.setFilter(getSuperClass()); if (dialog.open() == TypeSelectionDialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates the new type using the entered field values. * * @param monitor a progress monitor to report progress. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ ICompilationUnit createdWorkingCopy= null; try { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= getTypeName(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ String packStatement= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ";" + lineDelimiter + lineDelimiter; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ createdWorkingCopy= (ICompilationUnit) parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), null); createdWorkingCopy.getBuffer().setContents(packStatement); imports= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false); // add an import that will be removed again. Having this import solves 14661 imports.addImport(pack.getElementName(), getTypeName()); String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, createdWorkingCopy); createdType= createdWorkingCopy.createType(content, null, false, new SubProgressMonitor(monitor, 3)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); // add imports that will be removed again. Having the imports solves 14661 IType[] topLevelTypes= parentCU.getTypes(); for (int i= 0; i < topLevelTypes.length; i++) { imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); } lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, parentCU); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so types can be resolved correctly imports.create(false, new SubProgressMonitor(monitor, 1)); ICompilationUnit cu= createdType.getCompilationUnit(); synchronized(cu) { cu.reconcile(); } createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1)); // add imports imports.create(false, new SubProgressMonitor(monitor, 1)); synchronized(cu) { cu.reconcile(); } ISourceRange range= createdType.getSourceRange(); IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { String fileComment= getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } cu.commit(false, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } fCreatedType= createdType; } finally { if (createdWorkingCopy != null) { createdWorkingCopy.destroy(); } monitor.done(); } } /** * Returns the created type. The method only returns a valid type * after <code>createType</code> has been called. * * @return the created type * @see #createType(IProgressMonitor) */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, ImportsManager imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename; buf.append(imports.addImport(qualifiedName)); } } private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); buf.append(imports.addImport(typename)); if (i < last) { buf.append(','); } } } } /* * Called from createType to construct the source for this type */ private String constructTypeStub(ImportsManager imports, String lineDelimiter, ICompilationUnit parentCU) { StringBuffer buf= new StringBuffer(); String typeComment= getTypeComment(parentCU); if (typeComment != null && typeComment.length() > 0) { buf.append(typeComment); buf.append(lineDelimiter); } int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append('{'); buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead */ protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { //deprecated } /** * Hook method that gets called from <code>createType</code> to support adding of * unanticipated methods, fields, and inner types to the created type. * <p> * Implementers can use any methods defined on <code>IType</code> to manipulate the * new type. * </p> * <p> * The source code of the new type will be formtted using the platform's formatter. Needed * imports are added by the wizard at the end of the type creation process using the given * import manager. * </p> * * @param newType the new type created via <code>createType</code> * @param imports an import manager which can be used to add new imports * @param monitor a progress monitor to report progress. Must not be <code>null</code> * * @see #createType(IProgressMonitor) */ protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException { // call for compatibility createTypeMembers(newType, ((ImportsManager)imports).getImportsStructure(), monitor); // default implementation does nothing // example would be // String mainMathod= "public void foo(Vector vec) {}" // createdType.createMethod(main, null, false, null); // imports.addImport("java.lang.Vector"); } /** * Hook mathod that gets called from <code>createType</code> to retrieve * a file comment. This default implementation returns the content of the * 'filecomment' template. * * @return the file comment or <code>null</code> if a file comment * is not desired */ protected String getFileComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doFileComments()) { String template= getTemplate("filecomment", parentCU, 0); //$NON-NLS-1$ if (isValidComment(template)) { return template; } } return null; } private boolean isValidComment(String template) { IScanner scanner= ToolFactory.createScanner(true, false, false, false); scanner.setSource(template.toCharArray()); try { int next= scanner.getNextToken(); while (next == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { next= scanner.getNextToken(); } return next == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { } return false; } /** * Hook method that gets called from <code>createType</code> to retrieve * a type comment. This default implementation returns the content of the * 'typecomment' template. * * @return the type comment or <code>null</code> if a type comment * is not desired */ protected String getTypeComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doCreateComments()) { String template= getTemplate("typecomment", parentCU, 0); //$NON-NLS-1$ if (isValidComment(template)) { return template; } } return null; } /** * @deprecated Use getTemplate(String,ICompilationUnit,int) */ protected String getTemplate(String name, ICompilationUnit parentCU) { return getTemplate(name, parentCU, 0); } /** * Returns the string resulting from evaluation the given template in * the context of the given compilation unit. * * @param name the template to be evaluated * @param parentCU the templates evaluation context * @param pos a source offset into the parent compilation unit. The * template is evalutated at the given source offset */ protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { try { Template[] templates= Templates.getInstance().getTemplates(name); if (templates.length > 0) { return JavaContext.evaluateTemplate(templates[0], parentCU, pos); } } catch (CoreException e) { JavaPlugin.log(e); } return null; } /** * @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor); } /** * Creates the bodies of all unimplemented methods and constructors and adds them to the type. * Method is typically called by implementers of <code>NewTypeWizardPage</code> to add * needed method and constructors. * * @param type the type for which the new methods and constructor are to be created * @param doConstructors if <code>true</code> unimplemented constructors are created * @param doUnimplementedMethods if <code>true</code> unimplemented methods are created * @param imports an import manager to add all neded import statements * @param monitor a progress monitor to report progress */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException { ArrayList newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure()); if (constructors != null) { for (int i= 0; i < constructors.length; i++) { newMethods.add(constructors[i]); } } } } if (doUnimplementedMethods) { String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports.getImportsStructure()); if (unimplemented != null) { for (int i= 0; i < unimplemented.length; i++) { newMethods.add(unimplemented[i]); } } } IMethod[] createdMethods= new IMethod[newMethods.size()]; for (int i= 0; i < newMethods.size(); i++) { String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n createdMethods[i]= type.createMethod(content, null, false, null); } return createdMethods; } // ---- creation ---------------- /** * Returns the runnable that creates the type using the current settings. * The returned runnable must be executed in the UI thread. * * @return the runnable to create the new type */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
25,169
Bug 25169 Eating CA: visual indication remains
1) set preference: Insert Proposals 2) open TestCase.java 3) enable segmentated view 4) select TestCase(String) 5) place cursor at Stri>I<ng 6) activate code assist 7) select String from the proposal list 8) press Ctrl 9) press Enter -> color indication remains although content assist window closed
verified fixed
6e33835
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-10-31T17:08:26Z
2002-10-22T09:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProposal.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.util.Assert; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; public class JavaCompletionProposal implements IJavaCompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2 { private String fDisplayString; private String fReplacementString; private int fReplacementOffset; private int fReplacementLength; private int fCursorPosition; private Image fImage; private IContextInformation fContextInformation; private int fContextInformationPosition; private ProposalInfo fProposalInfo; private char[] fTriggerCharacters; protected boolean fToggleEating; protected ITextViewer fTextViewer; private int fRelevance; private StyleRange fRememberedStyleRange; /** * Creates a new completion proposal. All fields are initialized based on the provided information. * * @param replacementString the actual string to be inserted into the document * @param replacementOffset the offset of the text to be replaced * @param replacementLength the length of the text to be replaced * @param image the image to display for this proposal * @param displayString the string to be displayed for the proposal * If set to <code>null</code>, the replacement string will be taken as display string. */ public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) { this(replacementString, replacementOffset, replacementLength, image, displayString, relevance, null); } /** * Creates a new completion proposal. All fields are initialized based on the provided information. * * @param replacementString the actual string to be inserted into the document * @param replacementOffset the offset of the text to be replaced * @param replacementLength the length of the text to be replaced * @param image the image to display for this proposal * @param displayString the string to be displayed for the proposal * @param viewer the text viewer for which this proposal is computed, may be <code>null</code> * If set to <code>null</code>, the replacement string will be taken as display string. */ public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, ITextViewer viewer) { Assert.isNotNull(replacementString); Assert.isTrue(replacementOffset >= 0); Assert.isTrue(replacementLength >= 0); fReplacementString= replacementString; fReplacementOffset= replacementOffset; fReplacementLength= replacementLength; fImage= image; fDisplayString= displayString != null ? displayString : replacementString; fRelevance= relevance; fTextViewer= viewer; fCursorPosition= replacementString.length(); fContextInformation= null; fContextInformationPosition= -1; fTriggerCharacters= null; fProposalInfo= null; } /** * Sets the context information. * @param contentInformation The context information associated with this proposal */ public void setContextInformation(IContextInformation contextInformation) { fContextInformation= contextInformation; fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1); } /** * Sets the trigger characters. * @param triggerCharacters The set of characters which can trigger the application of this completion proposal */ public void setTriggerCharacters(char[] triggerCharacters) { fTriggerCharacters= triggerCharacters; } /** * Sets the proposal info. * @param additionalProposalInfo The additional information associated with this proposal or <code>null</code> */ public void setProposalInfo(ProposalInfo proposalInfo) { fProposalInfo= proposalInfo; } /** * Sets the cursor position relative to the insertion offset. By default this is the length of the completion string * (Cursor positioned after the completion) * @param cursorPosition The cursorPosition to set */ public void setCursorPosition(int cursorPosition) { Assert.isTrue(cursorPosition >= 0); fCursorPosition= cursorPosition; fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1); } /* * @see ICompletionProposalExtension#apply(IDocument, char, int) */ public void apply(IDocument document, char trigger, int offset) { try { // patch replacement length int delta= offset - (fReplacementOffset + fReplacementLength); if (delta > 0) fReplacementLength += delta; String string; if (trigger == (char) 0) { string= fReplacementString; } else { StringBuffer buffer= new StringBuffer(fReplacementString); // fix for PR #5533. Assumes that no eating takes place. if ((fCursorPosition > 0 && fCursorPosition <= buffer.length() && buffer.charAt(fCursorPosition - 1) != trigger)) { buffer.insert(fCursorPosition, trigger); ++fCursorPosition; } string= buffer.toString(); } replace(document, fReplacementOffset, fReplacementLength, string); if (fTextViewer != null && string != null) { int index= string.indexOf("()"); //$NON-NLS-1$ if (index != -1) { IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore(); if (preferenceStore.getBoolean(CompilationUnitEditor.CLOSE_BRACKETS)) { int newOffset= fReplacementOffset + index; LinkedPositionManager manager= new LinkedPositionManager(document); manager.addPosition(newOffset + 1, 0); LinkedPositionUI editor= new LinkedPositionUI(fTextViewer, manager); editor.setExitPolicy(new ExitPolicy(')')); editor.setFinalCaretOffset(newOffset + 2); editor.enter(); } } } } catch (BadLocationException x) { // ignore } } private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { final char fExitCharacter; public ExitPolicy(char exitCharacter) { fExitCharacter= exitCharacter; } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (manager.anyPositionIncludes(offset, length)) return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false); else return new ExitFlags(LinkedPositionUI.COMMIT, true); } switch (event.character) { case '\b': if (manager.getFirstPosition().length == 0) return new ExitFlags(0, true); else return null; case '\n': case '\r': return new ExitFlags(LinkedPositionUI.COMMIT, true); default: return null; } } } // #6410 - File unchanged but dirtied by code assist private void replace(IDocument document, int offset, int length, String string) throws BadLocationException { if (!document.get(offset, length).equals(string)) document.replace(offset, length, string); } /* * @see ICompletionProposal#apply */ public void apply(IDocument document) { apply(document, (char) 0, fReplacementOffset + fReplacementLength); } /* * @see ICompletionProposal#getSelection */ public Point getSelection(IDocument document) { return new Point(fReplacementOffset + fCursorPosition, 0); } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return fContextInformation; } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return fImage; } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { return fDisplayString; } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { if (fProposalInfo != null) { return fProposalInfo.getInfo(); } return null; } /* * @see ICompletionProposalExtension#getTriggerCharacters() */ public char[] getTriggerCharacters() { return fTriggerCharacters; } /* * @see ICompletionProposalExtension#getContextInformationPosition() */ public int getContextInformationPosition() { return fReplacementOffset + fContextInformationPosition; } /** * Gets the replacement offset. * @return Returns a int */ public int getReplacementOffset() { return fReplacementOffset; } /** * Sets the replacement offset. * @param replacementOffset The replacement offset to set */ public void setReplacementOffset(int replacementOffset) { Assert.isTrue(replacementOffset >= 0); fReplacementOffset= replacementOffset; } /** * Gets the replacement length. * @return Returns a int */ public int getReplacementLength() { return fReplacementLength; } /** * Sets the replacement length. * @param replacementLength The replacementLength to set */ public void setReplacementLength(int replacementLength) { Assert.isTrue(replacementLength >= 0); fReplacementLength= replacementLength; } /** * Gets the replacement string. * @return Returns a String */ public String getReplacementString() { return fReplacementString; } /** * Sets the replacement string. * @param replacementString The replacement string to set */ public void setReplacementString(String replacementString) { fReplacementString= replacementString; } /** * Sets the image. * @param image The image to set */ public void setImage(Image image) { fImage= image; } /* * @see ICompletionProposalExtension#isValidFor(IDocument, int) */ public boolean isValidFor(IDocument document, int offset) { return validate(document, offset, null); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent) */ public boolean validate(IDocument document, int offset, DocumentEvent event) { if (offset < fReplacementOffset) return false; /* * See http://dev.eclipse.org/bugs/show_bug.cgi?id=17667 String word= fReplacementString; */ boolean validated= startsWith(document, offset, fDisplayString); if (validated && event != null) { // adapt replacement range to document change int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength; fReplacementLength += delta; } return validated; } /** * Gets the proposal's relevance. * @return Returns a int */ public int getRelevance() { return fRelevance; } /** * Sets the proposal's relevance. * @param relevance The relevance to set */ public void setRelevance(int relevance) { fRelevance= relevance; } /** * Returns <code>true</code> if a words starts with the code completion prefix in the document, * <code>false</code> otherwise. */ protected boolean startsWith(IDocument document, int offset, String word) { int wordLength= word == null ? 0 : word.length(); if (offset > fReplacementOffset + wordLength) return false; try { int length= offset - fReplacementOffset; String start= document.get(fReplacementOffset, length); return word.substring(0, length).equalsIgnoreCase(start); } catch (BadLocationException x) { } return false; } private static boolean insertCompletion() { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); return preference.getBoolean(ContentAssistPreference.INSERT_COMPLETION); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension1#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document= viewer.getDocument(); fToggleEating= (stateMask & SWT.CTRL) != 0; if (insertCompletion() ^ fToggleEating) fReplacementLength= offset - fReplacementOffset; apply(document, trigger, offset); fToggleEating= false; } private static Color getForegroundColor(StyledText text) { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.COMPLETION_REPLACEMENT_FOREGROUND); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private static Color getBackgroundColor(StyledText text) { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.COMPLETION_REPLACEMENT_BACKGROUND); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private void repairPresentation(ITextViewer viewer) { if (fRememberedStyleRange != null) { if (viewer instanceof ITextViewerExtension2) { // attempts to reduce the redraw area ITextViewerExtension2 viewer2= (ITextViewerExtension2) viewer; viewer2.invalidateTextPresentation(fRememberedStyleRange.start, fRememberedStyleRange.length); } else viewer.invalidateTextPresentation(); } } private void updateStyle(ITextViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; IRegion visibleRegion= viewer.getVisibleRegion(); int caretOffset= text.getCaretOffset() + visibleRegion.getOffset(); if (caretOffset >= fReplacementOffset + fReplacementLength) { repairPresentation(viewer); return; } int offset= caretOffset - visibleRegion.getOffset(); int length= fReplacementOffset + fReplacementLength - caretOffset; Color foreground= getForegroundColor(text); Color background= getBackgroundColor(text); repairPresentation(viewer); fRememberedStyleRange= new StyleRange(offset, length, foreground, background); text.setStyleRange(fRememberedStyleRange); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(ITextViewer, boolean) */ public void selected(ITextViewer viewer, boolean smartToggle) { if (!insertCompletion() ^ smartToggle) updateStyle(viewer); else { repairPresentation(viewer); fRememberedStyleRange= null; } } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(ITextViewer) */ public void unselected(ITextViewer viewer) { repairPresentation(viewer); fRememberedStyleRange= null; } }
25,002
Bug 25002 [outline view] Add Go Into like functionality
Problem: The java outline view currently shows an outline of the entire CU, though most uses are only interested in the outline of the class itself. Because of the tree nature of the view, a fair amount of screen space is wasted on whitespace in front of the methods. It would be nice to be able to eliminate this whitespace by providing the ability to view only the class portion of the CU, either through a preference, or Go Into functionality like the Package Explorer. The second option would be preferrable, in order to deal with multiple classes/CU.
verified fixed
d4bd378
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-04T16:51:40Z
2002-10-17T15: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.List; import java.util.Vector; import org.eclipse.core.resources.IResource; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProviderChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.IActionBars; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator; import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.JdtActionConstants; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * The content outline page of the Java editor. The viewer implements a proprietary * update mechanism based on Java model deltas. It does not react on domain changes. * It is specified to show the content of ICompilationUnits and IClassFiles. * Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>. */ 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) { if (getControl() == null) return; 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; protected boolean matches(IJavaElement element) { if (element.getElementType() == IJavaElement.METHOD) { String name= element.getElementName(); return (name != null && name.indexOf('<') >= 0); } return false; } protected IJavaElement[] filter(IJavaElement[] children) { boolean initializers= false; for (int i= 0; i < children.length; i++) { if (matches(children[i])) { initializers= true; break; } } if (!initializers) return children; Vector v= new Vector(); for (int i= 0; i < children.length; i++) { if (matches(children[i])) continue; v.addElement(children[i]); } IJavaElement[] result= new IJavaElement[v.size()]; v.copyInto(result); return result; } public Object[] getChildren(Object parent) { if (parent instanceof IParent) { IParent c= (IParent) parent; try { return filter(c.getChildren()); } catch (JavaModelException x) { JavaPlugin.log(x); //$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.log(x); } } return false; } public boolean isDeleted(Object o) { return false; } public void dispose() { if (fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; } } /* * @see IContentProvider#inputChanged(Viewer, Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { boolean isCU= (newInput instanceof ICompilationUnit); if (isCU && fListener == null) { fListener= new ElementChangedListener(); JavaCore.addElementChangedListener(fListener); } else if (!isCU && fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; } } }; class JavaOutlineViewer extends TreeViewer { /** * Indicates an item which has been reused. At the point of * its reuse it has been expanded. This field is used to * communicate between <code>internalExpandToLevel</code> and * <code>reuseTreeItem</code>. */ private Item fReusedExpandedItem; 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 && !w.isDisposed()) 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; } protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) { if (element instanceof IMethod) { if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { try { return ((IMethod)element).isMainMethod(); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } return "main".equals(element.getElementName()); //$NON-NLS-1$ } return false; } protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException { if (element instanceof IMember && !(element instanceof IInitializer)) return ((IMember) element).getNameRange(); if (element instanceof ISourceReference) return ((ISourceReference) element).getSourceRange(); return null; } protected boolean overlaps(ISourceRange range, int start, int end) { return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end; } protected boolean filtered(IJavaElement parent, IJavaElement child) { Object[] result= new Object[] { child }; ViewerFilter[] filters= getFilters(); for (int i= 0; i < filters.length; i++) { result= filters[i].filter(this, parent, result); if (result.length == 0) return true; } return false; } protected void update(Widget w, IJavaElementDelta delta) { Item item; IJavaElement parent= delta.getElement(); IJavaElementDelta[] affected= delta.getAffectedChildren(); Item[] children= getChildren(w); boolean doUpdateParent= false; Vector deletions= new Vector(); Vector additions= new Vector(); for (int i= 0; i < affected.length; i++) { IJavaElementDelta affectedDelta= affected[i]; IJavaElement affectedElement= affectedDelta.getElement(); int status= affected[i].getKind(); // find tree item with affected element int j; for (j= 0; j < children.length; j++) if (affectedElement.equals(children[j].getData())) break; if (j == children.length) { // addition if ((status & IJavaElementDelta.CHANGED) != 0 && (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 && !filtered(parent, affectedElement)) { additions.addElement(affectedDelta); } continue; } item= children[j]; // removed if ((status & IJavaElementDelta.REMOVED) != 0) { deletions.addElement(item); doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); // changed } else if ((status & IJavaElementDelta.CHANGED) != 0) { int change= affectedDelta.getFlags(); doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { if (filtered(parent, affectedElement)) deletions.addElement(item); else updateItem(item, affectedElement); } if ((change & IJavaElementDelta.F_CONTENT) != 0) updateItem(item, affectedElement); if ((change & IJavaElementDelta.F_CHILDREN) != 0) update(item, affectedDelta); } } // find all elements to add IJavaElementDelta[] add= delta.getAddedChildren(); if (additions.size() > 0) { IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()]; System.arraycopy(add, 0, tmp, 0, add.length); for (int i= 0; i < additions.size(); i++) tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i); add= tmp; } // add at the right position go2: for (int i= 0; i < add.length; i++) { try { IJavaElement e= add[i].getElement(); if (filtered(parent, e)) continue go2; doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e); ISourceRange rng= getSourceRange(e); int start= rng.getOffset(); int end= start + rng.getLength() - 1; Item last= null; item= null; children= getChildren(w); for (int j= 0; j < children.length; j++) { item= children[j]; IJavaElement r= (IJavaElement) item.getData(); if (r == null) { // parent node collapsed and not be opened before -> do nothing continue go2; } try { rng= getSourceRange(r); if (overlaps(rng, start, end)) { // be tolerant if the delta is not correct, or if // the tree has been updated other than by a delta reuseTreeItem(item, e); continue go2; } else if (rng.getOffset() > start) { if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, (Object) e); } else { // nothing to reuse createTreeItem(w, (Object) e, j); } continue go2; } } catch (JavaModelException x) { // stumbled over deleted element } last= item; } // add at the end of the list if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, e); } else { // nothing to reuse createTreeItem(w, e, -1); } } catch (JavaModelException x) { // the element to be added is not present -> don't add it } } // remove items which haven't been reused Enumeration e= deletions.elements(); while (e.hasMoreElements()) { item= (Item) e.nextElement(); disassociate(item); item.dispose(); } if (doUpdateParent) updateItem(w, delta.getElement()); } /* * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) */ protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { Object input= getInput(); if (event instanceof ProblemsLabelChangedEvent) { ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; if (e.isMarkerChange() && input instanceof ICompilationUnit) { return; // marker changes can be ignored } } // look if the underlying resource changed Object[] changed= event.getElements(); if (changed != null) { IResource resource= getUnderlyingResource(); if (resource != null) { for (int i= 0; i < changed.length; i++) { if (changed[i].equals(resource)) { // change event to a full refresh event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource()); break; } } } } super.handleLabelProviderChanged(event); } private IResource getUnderlyingResource() { Object input= getInput(); if (input instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit) input; if (cu.isWorkingCopy()) { return cu.getOriginalElement().getResource(); } else { return cu.getResource(); } } else if (input instanceof IClassFile) { return ((IClassFile) input).getResource(); } return null; } }; class LexicalSortingAction extends Action { private JavaElementSorter fSorter= new JavaElementSorter(); public LexicalSortingAction() { super(); WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$ valueChanged(checked, false); } public void run() { valueChanged(isChecked(), true); } private void valueChanged(final boolean on, boolean store) { setChecked(on); BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() { public void run() { fOutlineViewer.setSorter(on ? fSorter : null); } }); if (store) JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$ } }; private IJavaElement fInput; private String fContextMenuID; private Menu fMenu; private JavaOutlineViewer fOutlineViewer; private JavaEditor fEditor; private MemberFilterActionGroup fMemberFilterActionGroup; private ListenerList fSelectionChangedListeners= new ListenerList(); private Hashtable fActions= new Hashtable(); private TogglePresentationAction fTogglePresentation; private ToggleTextHoverAction fToggleTextHover; private GotoErrorAction fPreviousError; private GotoErrorAction fNextError; private TextOperationAction fShowJavadoc; private TextOperationAction fUndo; private TextOperationAction fRedo; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; private IPropertyChangeListener fPropertyChangeListener; public JavaOutlinePage(String contextMenuID, JavaEditor editor) { super(); Assert.isNotNull(editor); fContextMenuID= contextMenuID; fEditor= editor; fTogglePresentation= new TogglePresentationAction(); fToggleTextHover= new ToggleTextHoverAction(); fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$ fPreviousError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR); fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$ fNextError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR); fShowJavadoc= (TextOperationAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO); fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO); fTogglePresentation.setEditor(editor); fToggleTextHover.setEditor(editor); fPreviousError.setEditor(editor); fNextError.setEditor(editor); fPropertyChangeListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doPropertyChange(event); } }; JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); } /* (non-Javadoc) * Method declared on Page */ public void init(IPageSite pageSite) { super.init(pageSite); } private void doPropertyChange(PropertyChangeEvent event) { if (fOutlineViewer != null) { if (MembersOrderPreferencePage.PREF_OUTLINE_SORT_OPTION.equals(event.getProperty())) { fOutlineViewer.refresh(); } } } /* * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) */ public void addSelectionChangedListener(ISelectionChangedListener listener) { if (fOutlineViewer != null) fOutlineViewer.addSelectionChangedListener(listener); else fSelectionChangedListeners.add(listener); } /* * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { if (fOutlineViewer != null) fOutlineViewer.removeSelectionChangedListener(listener); else fSelectionChangedListeners.remove(listener); } /* * @see ISelectionProvider#setSelection(ISelection) */ public void setSelection(ISelection selection) { if (fOutlineViewer != null) fOutlineViewer.setSelection(selection); } /* * @see ISelectionProvider#getSelection() */ public ISelection getSelection() { if (fOutlineViewer == null) return StructuredSelection.EMPTY; return fOutlineViewer.getSelection(); } private void registerToolbarActions() { IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager(); if (toolBarManager != null) { Action action= new LexicalSortingAction(); toolBarManager.add(action); fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$ fMemberFilterActionGroup.contributeToToolBar(toolBarManager); } } /* * @see IPage#createControl */ public void createControl(Composite parent) { Tree tree= new Tree(parent, SWT.MULTI); ILabelProvider lprovider= new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS, AppearanceAwareLabelProvider.getDecorators(true, new OverrideIndicatorLabelDecorator(null)) ); fOutlineViewer= new JavaOutlineViewer(tree); fOutlineViewer.setContentProvider(new ChildrenProvider()); fOutlineViewer.setLabelProvider(new DecoratingLabelProvider(lprovider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { fSelectionChangedListeners.remove(listeners[i]); fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]); } MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { contextMenuAboutToShow(manager); } }); fMenu= manager.createContextMenu(tree); tree.setMenu(fMenu); IPageSite site= getSite(); site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ site.setSelectionProvider(fOutlineViewer); // we must create the groups after we have set the selection provider to the site fActionGroups= new CompositeActionGroup(new ActionGroup[] { new OpenViewActionGroup(this), new ShowActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new GenerateActionGroup(this), new JavaSearchActionGroup(this)}); // register global actions IActionBars bars= site.getActionBars(); bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo); bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo); bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError); bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError); bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc); bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation); bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_TEXT_HOVER, fToggleTextHover); // http://dev.eclipse.org/bugs/show_bug.cgi?id=18968 bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError); bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError); fActionGroups.fillActionBars(bars); IStatusLineManager statusLineManager= site.getActionBars().getStatusLineManager(); if (statusLineManager != null) { StatusBarUpdater updater= new StatusBarUpdater(statusLineManager); fOutlineViewer.addSelectionChangedListener(updater); } registerToolbarActions(); fOutlineViewer.setInput(fInput); fOutlineViewer.getControl().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { handleKeyReleased(e); } }); initDragAndDrop(); } public void dispose() { if (fEditor == null) return; fEditor.outlinePageClosed(); fEditor= null; Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; i++) fSelectionChangedListeners.remove(listeners[i]); fSelectionChangedListeners= null; if (fPropertyChangeListener != null) { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fMenu != null && !fMenu.isDisposed()) { fMenu.dispose(); fMenu= null; } if (fActionGroups != null) fActionGroups.dispose(); fTogglePresentation.setEditor(null); fToggleTextHover.setEditor(null); fPreviousError.setEditor(null); fNextError.setEditor(null); fOutlineViewer= null; super.dispose(); } public Control getControl() { if (fOutlineViewer != null) return fOutlineViewer.getControl(); return null; } public void setInput(IJavaElement inputElement) { fInput= inputElement; if (fOutlineViewer != null) fOutlineViewer.setInput(fInput); } public void select(ISourceReference reference) { if (fOutlineViewer != null) { ISelection s= fOutlineViewer.getSelection(); if (s instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection) s; List elements= ss.toList(); if (!elements.contains(reference)) { s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference)); fOutlineViewer.setSelection(s, true); } } } } public void setAction(String actionID, IAction action) { Assert.isNotNull(actionID); if (action == null) fActions.remove(actionID); else fActions.put(actionID, action); } public IAction getAction(String actionID) { Assert.isNotNull(actionID); return (IAction) fActions.get(actionID); } /** * Convenience method to add the action installed under the given actionID to the * specified group of the menu. */ protected void addAction(IMenuManager menu, String group, String actionID) { IAction action= getAction(actionID); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (action.isEnabled()) { IMenuManager subMenu= menu.findMenuUsingPath(group); if (subMenu != null) subMenu.add(action); else menu.appendToGroup(group, action); } } } protected void contextMenuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); IStructuredSelection selection= (IStructuredSelection)getSelection(); fActionGroups.setContext(new ActionContext(selection)); fActionGroups.fillContextMenu(menu); } /* * @see Page#setFocus() */ public void setFocus() { if (fOutlineViewer != null) fOutlineViewer.getControl().setFocus(); } /** * Checkes whether a given Java element is an inner type. */ private boolean isInnerType(IJavaElement element) { if (element.getElementType() == IJavaElement.TYPE) { IJavaElement parent= element.getParent(); int type= parent.getElementType(); return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE); } return false; } /** * Handles key events in viewer. */ private void handleKeyReleased(KeyEvent event) { if (event.stateMask != 0) return; IAction action= null; if (event.character == SWT.DEL) { action= fCCPActionGroup.getDeleteAction(); } if (action != null && action.isEnabled()) action.run(); } private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fOutlineViewer) }; fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); // Drag Adapter Control control= fOutlineViewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fOutlineViewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners)); }}
25,517
Bug 25517 JVM crashes on method rename with circular dependecies in the classpath
I am reporting this bug for a WSAD customer. I have a simple scenario that will crash the Eclipse workbench. The key to making the crash happen seems to be that I need to have two projects whose classpath is dependent on each other with each dependency exported. I will attach two .zip files- each containing a Java Project that exhibit this behavior. Here are the steps to follow: - Unzip each of these projects into your workspace. - Start Eclipse - verify that IafConfigurationEJB is dependentent on IafConfigurationJAVA and vice versa inthe Java Build Paths page. Also notice that each dependendency is exported. - Open the com.deere.u90.iaf.configuration.ConfigurationPropertiesHelper class. In the Outline view, select the GetDefaultDirectory() method and select Refactor->Rename. Rename the method to GetDefaultDirectoryXX() and select the Next button. The JVM will crash and the Eclipse will come down. Note that if you remove the exports or the circular dependency, the crash does not occur.
resolved fixed
32f884c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-06T11:06:49Z
2002-10-29T22:20:00Z
org.eclipse.jdt.ui/core
25,517
Bug 25517 JVM crashes on method rename with circular dependecies in the classpath
I am reporting this bug for a WSAD customer. I have a simple scenario that will crash the Eclipse workbench. The key to making the crash happen seems to be that I need to have two projects whose classpath is dependent on each other with each dependency exported. I will attach two .zip files- each containing a Java Project that exhibit this behavior. Here are the steps to follow: - Unzip each of these projects into your workspace. - Start Eclipse - verify that IafConfigurationEJB is dependentent on IafConfigurationJAVA and vice versa inthe Java Build Paths page. Also notice that each dependendency is exported. - Open the com.deere.u90.iaf.configuration.ConfigurationPropertiesHelper class. In the Outline view, select the GetDefaultDirectory() method and select Refactor->Rename. Rename the method to GetDefaultDirectoryXX() and select the Next button. The JVM will crash and the Eclipse will come down. Note that if you remove the exports or the circular dependency, the crash does not occur.
resolved fixed
32f884c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-06T11:06:49Z
2002-10-29T22:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringScopeFactory.java
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
extension/org/eclipse/jdt/internal/corext/dom/LocalVariableIndex.java
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/flow/InputFlowAnalyzer.java
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/InlineMethodAction.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.actions; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter; import org.eclipse.jdt.internal.ui.refactoring.code.InlineMethodWizard; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Inlines the body of a method for a single call. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.1 */ public class InlineMethodAction extends SelectionDispatchAction { private CompilationUnitEditor fEditor; private static final String DIALOG_TITLE= "Inline Method"; /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public InlineMethodAction(CompilationUnitEditor editor) { super(editor.getEditorSite()); fEditor= editor; setText("Inline Method..."); update(null); } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void update(ISelection selection) { setEnabled(getCompilationUnit() != null); } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void run(ITextSelection selection) { ICompilationUnit cu= getCompilationUnit(); if (cu == null) return; InlineMethodRefactoring refactoring= InlineMethodRefactoring.create( cu, selection.getOffset(), selection.getLength(), JavaPreferencesSettings.getCodeGenerationSettings()); if (refactoring == null) { MessageDialog.openInformation(getShell(), DIALOG_TITLE, "No method invocation or declaration selected."); return; } try { IRewriteTarget target= (IRewriteTarget) fEditor.getAdapter(IRewriteTarget.class); try { target.beginCompoundChange(); new RefactoringStarter().activate(refactoring, createWizard(refactoring), DIALOG_TITLE, false); } finally { if (target != null) target.endCompoundChange(); } } catch (JavaModelException e) { ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, "Unexpected exception during operation"); } } private ICompilationUnit getCompilationUnit() { return SelectionConverter.getInputAsCompilationUnit(fEditor); } private RefactoringWizard createWizard(InlineMethodRefactoring refactoring) { return new InlineMethodWizard(refactoring); } }
24,908
Bug 24908 inline method - NPE when inlining into static methods [refactoring]
I-20021016 linux-gtk: public class Hoo { static { foo(); } private static void foo() { System.out.println("foo"); } } 1. select either use or declaration of foo 2. inline method 3. press finish 4. get an error dialog and log for NPE --8<--log--- !ENTRY org.eclipse.jdt.ui 4 1 Oct 17, 2002 12:13:21.76 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.LocalVariableIndex.perform (LocalVariableIndex.java:19) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initializeState (CallInliner.java:356) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize (CallInliner.java:147) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkIn put(InlineMethodRefactoring.java:182) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:116) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:299) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:343) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:473) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:574) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:543) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1403) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
b3e24be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-07T10:00:35Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OpenAction.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.util.Iterator; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IStorage; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.util.OpenStrategy; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceReference; 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.JavaStatusConstants; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.OpenActionUtil; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * This action opens a Java editor on a Java element or file. * <p> * The action is applicable to selections containing elements of * type <code>ICompilationUnit</code>, <code>IMember</code> * or <code>IFile</code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class OpenAction extends SelectionDispatchAction { private JavaEditor fEditor; /** * Creates a new <code>OpenAction</code>. The action requires * that the selection provided by the site's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param site the site providing context information for this action */ public OpenAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("OpenAction.label")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("OpenAction.tooltip")); //$NON-NLS-1$ setDescription(ActionMessages.getString("OpenAction.description")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.OPEN_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public OpenAction(JavaEditor editor) { this(editor.getEditorSite()); fEditor= editor; setText(ActionMessages.getString("OpenAction.declaration.label")); //$NON-NLS-1$ setEnabled(SelectionConverter.canOperateOn(fEditor)); } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ protected void selectionChanged(ITextSelection selection) { } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ protected void selectionChanged(IStructuredSelection selection) { setEnabled(checkEnabled(selection)); } private boolean checkEnabled(IStructuredSelection selection) { if (selection.isEmpty()) return false; for (Iterator iter= selection.iterator(); iter.hasNext();) { Object element= (Object)iter.next(); if (element instanceof ISourceReference) continue; if (element instanceof IResource) continue; if (element instanceof IStorage) continue; return false; } return true; } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ protected void run(ITextSelection selection) { try { IJavaElement element= SelectionConverter.codeResolve(fEditor, getShell(), getDialogTitle(), ActionMessages.getString("OpenAction.select_element")); //$NON-NLS-1$ if (element == null) { IEditorStatusLine statusLine= (IEditorStatusLine) fEditor.getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(true, ActionMessages.getString("OpenAction.error.messageBadSelection"), null); //$NON-NLS-1$ getShell().getDisplay().beep(); return; } IJavaElement input= SelectionConverter.getInput(fEditor); int type= element.getElementType(); if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT) element= input; run(new Object[] {element} ); } catch (JavaModelException e) { showError(e); } } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ protected void run(IStructuredSelection selection) { if (!checkEnabled(selection)) return; run(selection.toArray()); } private void run(Object[] elements) { if (elements == null) return; for (int i= 0; i < elements.length; i++) { Object element= elements[i]; try { element= getElementToOpen(element); boolean activateOnOpen= fEditor != null ? true : OpenStrategy.activateOnOpen(); OpenActionUtil.open(element, activateOnOpen); } catch (JavaModelException e) { JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, ActionMessages.getString("OpenAction.error.message"), e)); //$NON-NLS-1$ ErrorDialog.openError(getShell(), getDialogTitle(), ActionMessages.getString("OpenAction.error.messageProblems"), //$NON-NLS-1$ e.getStatus()); } catch (PartInitException x) { String name= null; if (element instanceof IJavaElement) { name= ((IJavaElement) element).getElementName(); } else if (element instanceof IStorage) { name= ((IStorage) element).getName(); } else if (element instanceof IResource) { name= ((IResource) element).getName(); } if (name != null) { MessageDialog.openError(getShell(), ActionMessages.getString("OpenAction.error.messageProblems"), //$NON-NLS-1$ ActionMessages.getFormattedString("OpenAction.error.messageArgs", //$NON-NLS-1$ new String[] { name, x.getMessage() } )); } } } } /** * Note: this method is for internal use only. Clients should not call this method. */ public Object getElementToOpen(Object object) throws JavaModelException { return object; } private String getDialogTitle() { return ActionMessages.getString("OpenAction.error.title"); //$NON-NLS-1$ } private void showError(CoreException e) { ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.getString("OpenAction.error.message")); //$NON-NLS-1$ } }
25,903
Bug 25903 AnnotationType.PROBLEM?
Why is there no PROBLEM annotation type? The method IAnnotationType.isProblem() has been deprecated.
closed fixed
4a88d0a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T08:55:41Z
2002-11-08T18:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/AnnotationType.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; /** * MarkerType.java */ public final class AnnotationType { public final static AnnotationType ALL= new AnnotationType(); public final static AnnotationType UNKNOWN= new AnnotationType(); public final static AnnotationType BOOKMARK= new AnnotationType(); public final static AnnotationType TASK= new AnnotationType(); public final static AnnotationType ERROR= new AnnotationType(); public final static AnnotationType WARNING= new AnnotationType(); public final static AnnotationType SEARCH_RESULT= new AnnotationType(); private AnnotationType() { } }
25,914
Bug 25914 Method signature refactor does not update Outline
I used the refactoring utility to change the type of one of the params in an interface. The utility completed successfully, but did not update the Outline window, which still shows the old signature.
verified fixed
1e17bfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T13:36:19Z
2002-11-08T18:26:40Z
org.eclipse.jdt.ui/ui
25,914
Bug 25914 Method signature refactor does not update Outline
I used the refactoring utility to change the type of one of the params in an interface. The utility completed successfully, but did not update the Outline window, which still shows the old signature.
verified fixed
1e17bfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T13:36:19Z
2002-11-08T18:26:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeSignatureInputPage.java
22,533
Bug 22533 [runtime] Preferences.contains() returns false even if property has been set
Build: 20020819 0. get store (instance of org.eclipse.core.runtime.Preferences) 1. use store.setValue('key', false); 2. use store.contains('key'); ==> returns false which is a severe bug in my opinion. Reason for the bug is that the key is removed from the store if the value is the same as the default value [ok]. There is a list with default values which is also checked when using contains [ok] but unfortunately the getDefaultBoolean method returns false even if there is no default [bug]. It should either return null or add the key to the default list as soon as returning 'false'
resolved wontfix
59857ba
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T14:08:13Z
2002-08-19T15:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/CustomFiltersActionGroup.java
25,794
Bug 25794 Buttons cut off in externalize strings dialog
I20021031 Linux/Motif. Open the Translate Strings dialog on a Java file. "Translate" is cut off at the top "Edit Key" is cut off at the bottom.
verified fixed
fd87172
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T14:37:14Z
2002-11-06T19:13:20Z
org.eclipse.jdt.ui/ui
25,794
Bug 25794 Buttons cut off in externalize strings dialog
I20021031 Linux/Motif. Open the Translate Strings dialog on a Java file. "Translate" is cut off at the top "Edit Key" is cut off at the bottom.
verified fixed
fd87172
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T14:37:14Z
2002-11-06T19:13:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java
25,900
Bug 25900 NPE in CompilationUnitEditor
Build I20021105++ - load JUnit - expand a CU - delete CU on disk - select a field of expanded CU - open type hierarchy ==> you get an editor saying that the file doesn't exist on disk - close editor java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.LinePainter.drawHighlightLine (LinePainter.java:110) at org.eclipse.jdt.internal.ui.javaeditor.LinePainter.deactivate (LinePainter.java:128) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.stopLineHighlightin g(CompilationUnitEditor.java:1142) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.dispose (CompilationUnitEditor.java:1350) at org.eclipse.ui.internal.WorkbenchPage$5.run(WorkbenchPage.java:910) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:839) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.WorkbenchPage.disposePart (WorkbenchPage.java:908) at org.eclipse.ui.internal.WorkbenchPage.closeEditor (WorkbenchPage.java:723) at org.eclipse.ui.internal.WorkbenchPage.closeEditor (WorkbenchPage.java:690) at org.eclipse.ui.internal.EditorPane.doHide(EditorPane.java:83) at org.eclipse.ui.internal.EditorWorkbook$1.itemClosed (EditorWorkbook.java:121) at org.eclipse.swt.custom.CTabFolder.closeNotify(CTabFolder.java:304) at org.eclipse.swt.custom.CTabFolder.access$13(CTabFolder.java:294) at org.eclipse.swt.custom.CTabFolder$4.handleEvent(CTabFolder.java:434) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1419) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1402) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24)
verified fixed
4618b77
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T15:04:55Z
2002-11-08T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.lang.reflect.InvocationTargetException; import java.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.custom.VerifyKeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.Position; 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.SourceViewerConfiguration; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.tasklist.TaskList; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction; import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionSourceViewer; import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; /** * Java specific text editor. */ public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant { interface ITextConverter { void customizeDocumentCommand(IDocument document, DocumentCommand command); }; class AdaptedRulerLayout extends Layout { protected int fGap; protected AdaptedSourceViewer fAdaptedSourceViewer; protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) { fGap= gap; fAdaptedSourceViewer= asv; } protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { Control[] children= composite.getChildren(); Point s= children[children.length - 1].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache); if (fAdaptedSourceViewer.isVerticalRulerVisible()) s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap; return s; } protected void layout(Composite composite, boolean flushCache) { Rectangle clArea= composite.getClientArea(); if (fAdaptedSourceViewer.isVerticalRulerVisible()) { StyledText textWidget= fAdaptedSourceViewer.getTextWidget(); Rectangle trim= textWidget.computeTrim(0, 0, 0, 0); int scrollbarHeight= trim.height; IVerticalRuler vr= fAdaptedSourceViewer.getVerticalRuler(); int vrWidth=vr.getWidth(); int orWidth= 0; if (fAdaptedSourceViewer.isOverviewRulerVisible()) { OverviewRuler or= fAdaptedSourceViewer.getOverviewRuler(); orWidth= or.getWidth(); or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight, orWidth, clArea.height - 3*scrollbarHeight); } textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth - 2*fGap, clArea.height); vr.getControl().setBounds(0, 0, vrWidth, clArea.height - scrollbarHeight); } else { StyledText textWidget= fAdaptedSourceViewer.getTextWidget(); textWidget.setBounds(0, 0, clArea.width, clArea.height); } } }; class AdaptedSourceViewer extends JavaCorrectionSourceViewer { private List fTextConverters; private OverviewRuler fOverviewRuler; private boolean fIsOverviewRulerVisible; private boolean fIgnoreTextConverters= false; private IVerticalRuler fCachedVerticalRuler; private boolean fCachedIsVerticalRulerVisible; public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { super(parent, ruler, styles, CompilationUnitEditor.this); fCachedVerticalRuler= ruler; fCachedIsVerticalRulerVisible= (ruler != null); fOverviewRuler= new OverviewRuler(VERTICAL_RULER_WIDTH); delayedCreateControl(parent, styles); } /* * @see ISourceViewer#showAnnotations(boolean) */ public void showAnnotations(boolean show) { fCachedIsVerticalRulerVisible= (show && fCachedVerticalRuler != null); super.showAnnotations(show); } public IContentAssistant getContentAssistant() { return fContentAssistant; } /* * @see ITextOperationTarget#doOperation(int) */ public void doOperation(int operation) { if (getTextWidget() == null) return; switch (operation) { case CONTENTASSIST_PROPOSALS: String msg= fContentAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case UNDO: fIgnoreTextConverters= true; break; case REDO: fIgnoreTextConverters= true; break; } super.doOperation(operation); } public void insertTextConverter(ITextConverter textConverter, int index) { throw new UnsupportedOperationException(); } public void addTextConverter(ITextConverter textConverter) { if (fTextConverters == null) { fTextConverters= new ArrayList(1); fTextConverters.add(textConverter); } else if (!fTextConverters.contains(textConverter)) fTextConverters.add(textConverter); } public void removeTextConverter(ITextConverter textConverter) { if (fTextConverters != null) { fTextConverters.remove(textConverter); if (fTextConverters.size() == 0) fTextConverters= null; } } /* * @see TextViewer#customizeDocumentCommand(DocumentCommand) */ protected void customizeDocumentCommand(DocumentCommand command) { super.customizeDocumentCommand(command); if (!fIgnoreTextConverters && fTextConverters != null) { for (Iterator e = fTextConverters.iterator(); e.hasNext();) ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command); } fIgnoreTextConverters= false; } public IVerticalRuler getVerticalRuler() { return fCachedVerticalRuler; } public boolean isVerticalRulerVisible() { return fCachedIsVerticalRulerVisible; } public OverviewRuler getOverviewRuler() { return fOverviewRuler; } /* * @see TextViewer#createControl(Composite, int) */ protected void createControl(Composite parent, int styles) { // do nothing here } protected void delayedCreateControl(Composite parent, int styles) { //create the viewer super.createControl(parent, styles); Control control= getControl(); if (control instanceof Composite) { Composite composite= (Composite) control; composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this)); fOverviewRuler.createControl(composite, this); } } public void hideOverviewRuler() { fIsOverviewRulerVisible= false; Control control= getControl(); if (control instanceof Composite) { Composite composite= (Composite) control; composite.layout(); } } public void showOverviewRuler() { fIsOverviewRulerVisible= true; Control control= getControl(); if (control instanceof Composite) { Composite composite= (Composite) control; composite.layout(); } } public boolean isOverviewRulerVisible() { return fIsOverviewRulerVisible; } /* * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int) */ public void setDocument(IDocument document, IAnnotationModel annotationModel, int visibleRegionOffset, int visibleRegionLength) { super.setDocument(document, annotationModel, visibleRegionOffset, visibleRegionLength); fOverviewRuler.setModel(annotationModel); } // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 public void updateIndentationPrefixes() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(this); for (int i= 0; i < types.length; i++) { String[] prefixes= configuration.getIndentPrefixes(this, types[i]); if (prefixes != null && prefixes.length > 0) setIndentPrefixes(prefixes, types[i]); } } /* * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) */ public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester); } }; static class TabConverter implements ITextConverter { private int fTabRatio; private ILineTracker fLineTracker; public TabConverter() { } public void setNumberOfSpacesPerTab(int ratio) { fTabRatio= ratio; } public void setLineTracker(ILineTracker lineTracker) { fLineTracker= lineTracker; } private int insertTabString(StringBuffer buffer, int offsetInLine) { if (fTabRatio == 0) return 0; int remainder= offsetInLine % fTabRatio; remainder= fTabRatio - remainder; for (int i= 0; i < remainder; i++) buffer.append(' '); return remainder; } public void customizeDocumentCommand(IDocument document, DocumentCommand command) { String text= command.text; if (text == null) return; int index= text.indexOf('\t'); if (index > -1) { StringBuffer buffer= new StringBuffer(); fLineTracker.set(command.text); int lines= fLineTracker.getNumberOfLines(); try { for (int i= 0; i < lines; i++) { int offset= fLineTracker.getLineOffset(i); int endOffset= offset + fLineTracker.getLineLength(i); String line= text.substring(offset, endOffset); int position= 0; if (i == 0) { IRegion firstLine= document.getLineInformationOfOffset(command.offset); position= command.offset - firstLine.getOffset(); } int length= line.length(); for (int j= 0; j < length; j++) { char c= line.charAt(j); if (c == '\t') { position += insertTabString(buffer, position); } else { buffer.append(c); ++ position; } } } command.text= buffer.toString(); } catch (BadLocationException x) { } } } }; private class PropertyChangeListener implements IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { handlePreferencePropertyChanged(event); } } /* Preference key for code formatter tab size */ private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; /** Preference key for matching brackets */ public final static String MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$ /** Preference key for matching brackets color */ public final static String MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$ /** Preference key for highlighting current line */ public final static String CURRENT_LINE= "currentLine"; //$NON-NLS-1$ /** Preference key for highlight color of current line */ public final static String CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$ /** Preference key for showing print marging ruler */ public final static String PRINT_MARGIN= "printMargin"; //$NON-NLS-1$ /** Preference key for print margin ruler color */ public final static String PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$ /** Preference key for print margin ruler column */ public final static String PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$ /** Preference key for inserting spaces rather than tabs */ public final static String SPACES_FOR_TABS= JavaSourceViewerConfiguration.SPACES_FOR_TABS; /** Preference key for error indication */ public final static String ERROR_INDICATION= "problemIndication"; //$NON-NLS-1$ /** Preference key for error color */ public final static String ERROR_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$ /** Preference key for warning indication */ public final static String WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$ /** Preference key for warning color */ public final static String WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$ /** Preference key for task indication */ public final static String TASK_INDICATION= "taskIndication"; //$NON-NLS-1$ /** Preference key for task color */ public final static String TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$ /** Preference key for bookmark indication */ public final static String BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$ /** Preference key for bookmark color */ public final static String BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$ /** Preference key for search result indication */ public final static String SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$ /** Preference key for search result color */ public final static String SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$ /** Preference key for unknown annotation indication */ public final static String UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$ /** Preference key for unknown annotation color */ public final static String UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$ /** Preference key for linked position color */ public final static String LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$ /** Preference key for shwoing the overview ruler */ public final static String OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$ /** Preference key for error indication in overview ruler */ public final static String ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$ /** Preference key for warning indication in overview ruler */ public final static String WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$ /** Preference key for task indication in overview ruler */ public final static String TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$ /** Preference key for bookmark indication in overview ruler */ public final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ /** Preference key for search result indication in overview ruler */ public final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ /** Preference key for unknown annotation indication in overview ruler */ public final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$ /** Preference key for automatically closing strings */ public final static String CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$ /** Preference key for automatically wrapping Java strings */ public final static String WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$ /** Preference key for automatically closing brackets and parenthesis */ public final static String CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$ /** Preference key for automatically closing javadocs and comments */ public final static String CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$ /** Preference key for automatically adding javadoc tags */ public final static String ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$ /** Preference key for automatically formatting javadocs */ public final static String FORMAT_JAVADOCS= "formatJavaDocs"; //$NON-NLS-1$ private final static class AnnotationInfo { public String fColorPreference; public String fOverviewRulerPreference; public String fEditorPreference; }; private final static Map ANNOTATION_MAP; static { AnnotationInfo info; ANNOTATION_MAP= new HashMap(); info= new AnnotationInfo(); info.fColorPreference= TASK_INDICATION_COLOR; info.fOverviewRulerPreference= TASK_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= TASK_INDICATION; ANNOTATION_MAP.put(AnnotationType.TASK, info); info= new AnnotationInfo(); info.fColorPreference= ERROR_INDICATION_COLOR; info.fOverviewRulerPreference= ERROR_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= ERROR_INDICATION; ANNOTATION_MAP.put(AnnotationType.ERROR, info); info= new AnnotationInfo(); info.fColorPreference= WARNING_INDICATION_COLOR; info.fOverviewRulerPreference= WARNING_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= WARNING_INDICATION; ANNOTATION_MAP.put(AnnotationType.WARNING, info); info= new AnnotationInfo(); info.fColorPreference= BOOKMARK_INDICATION_COLOR; info.fOverviewRulerPreference= BOOKMARK_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= BOOKMARK_INDICATION; ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info); info= new AnnotationInfo(); info.fColorPreference= SEARCH_RESULT_INDICATION_COLOR; info.fOverviewRulerPreference= SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= SEARCH_RESULT_INDICATION; ANNOTATION_MAP.put(AnnotationType.SEARCH_RESULT, info); info= new AnnotationInfo(); info.fColorPreference= UNKNOWN_INDICATION_COLOR; info.fOverviewRulerPreference= UNKNOWN_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= UNKNOWN_INDICATION; ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info); }; private final static AnnotationType[] ANNOTATION_LAYERS= new AnnotationType[] { AnnotationType.UNKNOWN, AnnotationType.BOOKMARK, AnnotationType.TASK, AnnotationType.SEARCH_RESULT, AnnotationType.WARNING, AnnotationType.ERROR }; /** 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 paint manager */ private PaintManager fPaintManager; /** The editor's bracket painter */ private BracketPainter fBracketPainter; /** The editor's bracket matcher */ private JavaPairMatcher fBracketMatcher; /** The editor's line painter */ private LinePainter fLinePainter; /** The editor's print margin ruler painter */ private PrintMarginPainter fPrintMarginPainter; /** The editor's problem painter */ private ProblemPainter fProblemPainter; /** The editor's tab converter */ private TabConverter fTabConverter; /** History for structure select action */ private SelectionHistory fSelectionHistory; /** The preference property change listener for java core. */ private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener(); /** The remembered java element */ private IJavaElement fRememberedElement; /** The remembered selection */ private ITextSelection fRememberedSelection; /** The remembered java element offset */ private int fRememberedElementOffset; /** The bracket inserter. */ private BracketInserter fBracketInserter= new BracketInserter(); /** The standard action groups added to the menu */ private GenerateActionGroup fGenerateActionGroup; private CompositeActionGroup fContextMenuGroup; /** * Creates a new compilation unit editor. */ public CompilationUnitEditor() { super(); setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider()); setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$ setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$ // don't set help contextId, we install our own help context fSavePolicy= null; fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this); } /* * @see AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, JavaCorrectionSourceViewer.CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction("ContentAssistProposal", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT); setAction("Comment", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT); setAction("Uncomment", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT); setAction("Format", action); //$NON-NLS-1$ markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$ markAsStateDependentAction("Comment", true); //$NON-NLS-1$ markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ markAsStateDependentAction("Format", true); //$NON-NLS-1$ action= new GotoMatchingBracketAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER); setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); fSelectionHistory= new SelectionHistory(this); action= new StructureSelectEnclosingAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING); setAction(StructureSelectionAction.ENCLOSING, action); action= new StructureSelectNextAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT); setAction(StructureSelectionAction.NEXT, action); action= new StructureSelectPreviousAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS); setAction(StructureSelectionAction.PREVIOUS, action); StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory); historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST); setAction(StructureSelectionAction.HISTORY, historyAction); fSelectionHistory.setHistoryAction(historyAction); fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); fActionGroups.addGroup(rg); fActionGroups.addGroup(fGenerateActionGroup); // We have to keep the context menu group separate to have better control over positioning fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup, rg, new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)}); } /* * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementAt(int offset) { return getElementAt(offset, true); } /** * Returns the most narrow element including the given offset. If <code>reconcile</code> * is <code>true</code> the editor's input element is reconciled in advance. If it is * <code>false</code> this method only returns a result if the editor's input element * does not need to be reconciled. * * @param offset the offset included by the retrieved element * @param reconcile <code>true</code> if working copy should be reconciled */ protected IJavaElement getElementAt(int offset, boolean reconcile) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { if (reconcile) { synchronized (unit) { unit.reconcile(); } return unit.getElementAt(offset); } else if (unit.isConsistent()) return unit.getElementAt(offset); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /* * @see JavaEditor#getCorrespondingElement(IJavaElement) */ protected IJavaElement getCorrespondingElement(IJavaElement element) { try { return EditorUtility.getWorkingCopy(element, true); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } return null; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$ ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /* * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) */ protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { if (page != null) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); page.setInput(manager.getWorkingCopy(input)); } } /* * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor) */ protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p; cp.setSavePolicy(fSavePolicy); } try { super.performSaveOperation(operation, progressMonitor); } finally { if (p instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p; cp.setSavePolicy(null); } } } /* * @see AbstractTextEditor#doSave(IProgressMonitor) */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) { // editor has been closed return; } if (p.isDeleted(getEditorInput())) { if (isSaveAsAllowed()) { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(progressMonitor); } else { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Missing resources. */ Shell shell= getSite().getShell(); MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { setStatusLineErrorMessage(null); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { performSaveOperation(createSaveOperation(false), progressMonitor); } } else performSaveOperation(createSaveOperation(false), progressMonitor); } } /** * Jumps to the error next according to the given direction. */ public void gotoError(boolean forward) { ISelectionProvider provider= getSelectionProvider(); ITextSelection s= (ITextSelection) provider.getSelection(); Position errorPosition= new Position(0, 0); IProblemAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition); if (nextError != null) { IMarker marker= null; if (nextError instanceof MarkerAnnotation) marker= ((MarkerAnnotation) nextError).getMarker(); else { Iterator e= nextError.getOverlaidIterator(); if (e != null) { while (e.hasNext()) { Object o= e.next(); if (o instanceof MarkerAnnotation) { marker= ((MarkerAnnotation) o).getMarker(); break; } } } } if (marker != null) { IWorkbenchPage page= getSite().getPage(); IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$ if (view instanceof TaskList) { StructuredSelection ss= new StructuredSelection(marker); ((TaskList) view).setSelection(ss, true); } } selectAndReveal(errorPosition.getOffset(), errorPosition.getLength()); setStatusLineErrorMessage(nextError.getMessage()); } else { setStatusLineErrorMessage(null); } } /** * Jumps to the matching bracket. */ public void gotoMatchingBracket() { if (fBracketMatcher == null) fBracketMatcher= new JavaPairMatcher(new char[] { '{', '}', '(', ')', '[', ']' }); ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); if (document == null) return; ISelectionProvider provider= getSelectionProvider(); ITextSelection selection= (ITextSelection) provider.getSelection(); int selectionLength= Math.abs(selection.getLength()); if (selectionLength > 1) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } IRegion region= fBracketMatcher.match(document, selection.getOffset()); if (region == null) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } int offset= region.getOffset(); int length= region.getLength(); if (length < 1) return; int anchor= fBracketMatcher.getAnchor(); int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset : offset + length - 1; IRegion visibleRegion= sourceViewer.getVisibleRegion(); if (targetOffset < visibleRegion.getOffset() || targetOffset >= visibleRegion.getOffset() + visibleRegion.getLength()) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } sourceViewer.setSelectedRange(targetOffset, selectionLength); sourceViewer.revealRange(targetOffset, selectionLength); } /** * Ses the given message as error message to this editor's status line. * @param msg message to be set */ protected void setStatusLineErrorMessage(String msg) { IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(true, msg, null); } private IProblemAnnotation getNextError(int offset, boolean forward, Position errorPosition) { IProblemAnnotation nextError= null; Position nextErrorPosition= null; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= 0; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= new ProblemAnnotationIterator(model, false); while (e.hasNext()) { IProblemAnnotation a= (IProblemAnnotation) e.next(); if (a.hasOverlay() || !a.isProblem()) continue; Position p= model.getPosition((Annotation) a); if (!p.includes(offset)) { int currentDistance= 0; if (forward) { currentDistance= p.getOffset() - offset; if (currentDistance < 0) currentDistance= endOfDocument - offset + p.getOffset(); } else { currentDistance= offset - p.getOffset(); if (currentDistance < 0) currentDistance= offset + endOfDocument - p.getOffset(); } if (nextError == null || currentDistance < distance) { distance= currentDistance; nextError= a; nextErrorPosition= p; } } } if (nextErrorPosition != null) { errorPosition.setOffset(nextErrorPosition.getOffset()); errorPosition.setLength(nextErrorPosition.getLength()); } return nextError; } /* * @see AbstractTextEditor#isSaveAsAllowed() */ public boolean isSaveAsAllowed() { return true; } /** * The compilation unit editor implementation of this <code>AbstractTextEditor</code> * method asks the user for the workspace path of a file resource and saves the document * there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); IEditorInput input = getEditorInput(); SaveAsDialog dialog= new SaveAsDialog(shell); IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; if (original != null) dialog.setOriginalFile(original); dialog.create(); IDocumentProvider provider= getDocumentProvider(); if (provider == null) { // editor has been programmatically closed while the dialog was open return; } if (provider.isDeleted(input) && original != null) { String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ dialog.setErrorMessage(null); dialog.setMessage(message, IMessageProvider.WARNING); } if (dialog.open() == Dialog.CANCEL) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IPath filePath= dialog.getResult(); if (filePath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IWorkspace workspace= ResourcesPlugin.getWorkspace(); IFile file= workspace.getRoot().getFile(filePath); final IEditorInput newInput= new FileEditorInput(file); WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(final IProgressMonitor monitor) throws CoreException { getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); } }; boolean success= false; try { provider.aboutToChange(newInput); new ProgressMonitorDialog(shell).run(false, true, op); success= true; } catch (InterruptedException x) { } catch (InvocationTargetException x) { Throwable t= x.getTargetException(); if (t instanceof CoreException) { CoreException cx= (CoreException) t; ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ } else { MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { provider.changed(newInput); if (success) setInput(newInput); } if (progressMonitor != null) progressMonitor.setCanceled(!success); } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); configureTabConverter(); } private void startBracketHighlighting() { if (fBracketPainter == null) { ISourceViewer sourceViewer= getSourceViewer(); fBracketPainter= new BracketPainter(sourceViewer); fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); fPaintManager.addPainter(fBracketPainter); } } private void stopBracketHighlighting() { if (fBracketPainter != null) { fPaintManager.removePainter(fBracketPainter); fBracketPainter.deactivate(true); fBracketPainter.dispose(); fBracketPainter= null; } } private boolean isBracketHighlightingEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(MATCHING_BRACKETS); } private void startLineHighlighting() { if (fLinePainter == null) { ISourceViewer sourceViewer= getSourceViewer(); fLinePainter= new LinePainter(sourceViewer); fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR)); fPaintManager.addPainter(fLinePainter); } } private void stopLineHighlighting() { if (fLinePainter != null) { fPaintManager.removePainter(fLinePainter); fLinePainter.deactivate(true); fLinePainter.dispose(); fLinePainter= null; } } private boolean isLineHighlightingEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(CURRENT_LINE); } private void showPrintMargin() { if (fPrintMarginPainter == null) { fPrintMarginPainter= new PrintMarginPainter(getSourceViewer()); fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); fPaintManager.addPainter(fPrintMarginPainter); } } private void hidePrintMargin() { if (fPrintMarginPainter != null) { fPaintManager.removePainter(fPrintMarginPainter); fPrintMarginPainter.deactivate(true); fPrintMarginPainter.dispose(); fPrintMarginPainter= null; } } private boolean isPrintMarginVisible() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(PRINT_MARGIN); } private void startAnnotationIndication(AnnotationType annotationType) { if (fProblemPainter == null) { fProblemPainter= new ProblemPainter(this, getSourceViewer()); fPaintManager.addPainter(fProblemPainter); } fProblemPainter.setColor(annotationType, getColor(annotationType)); fProblemPainter.paintAnnotations(annotationType, true); fProblemPainter.paint(IPainter.CONFIGURATION); } private void shutdownAnnotationIndication() { if (fProblemPainter != null) { if (!fProblemPainter.isPaintingAnnotations()) { fPaintManager.removePainter(fProblemPainter); fProblemPainter.deactivate(true); fProblemPainter.dispose(); fProblemPainter= null; } else { fProblemPainter.paint(IPainter.CONFIGURATION); } } } private void stopAnnotationIndication(AnnotationType annotationType) { if (fProblemPainter != null) { fProblemPainter.paintAnnotations(annotationType, false); shutdownAnnotationIndication(); } } private boolean isAnnotationIndicationEnabled(AnnotationType annotationType) { IPreferenceStore store= getPreferenceStore(); AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType); if (info != null) return store.getBoolean(info.fEditorPreference); return false; } private boolean isAnnotationIndicationInOverviewRulerEnabled(AnnotationType annotationType) { IPreferenceStore store= getPreferenceStore(); AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType); if (info != null) return store.getBoolean(info.fOverviewRulerPreference); return false; } private void showAnnotationIndicationInOverviewRuler(AnnotationType annotationType, boolean show) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); OverviewRuler ruler= asv.getOverviewRuler(); if (ruler != null) { ruler.setColor(annotationType, getColor(annotationType)); ruler.showAnnotation(annotationType, show); ruler.update(); } } private void setColorInOverviewRuler(AnnotationType annotationType, Color color) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); OverviewRuler ruler= asv.getOverviewRuler(); if (ruler != null) { ruler.setColor(annotationType, color); ruler.update(); } } private void configureTabConverter() { if (fTabConverter != null) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cup= (CompilationUnitDocumentProvider) provider; fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); } } } private int getTabSize() { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); return preferences.getInt(CODE_FORMATTER_TAB_SIZE); } private void startTabConversion() { if (fTabConverter == null) { fTabConverter= new TabConverter(); configureTabConverter(); fTabConverter.setNumberOfSpacesPerTab(getTabSize()); AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.addTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); } } private void stopTabConversion() { if (fTabConverter != null) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.removeTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); fTabConverter= null; } } private boolean isTabConversionEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(SPACES_FOR_TABS); } private void showOverviewRuler() { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.showOverviewRuler(); OverviewRuler overviewRuler= asv.getOverviewRuler(); if (overviewRuler != null) { for (int i= 0; i < ANNOTATION_LAYERS.length; i++) { AnnotationType type= ANNOTATION_LAYERS[i]; overviewRuler.setLayer(type, i); if (isAnnotationIndicationInOverviewRulerEnabled(type)) showAnnotationIndicationInOverviewRuler(type, true); } } } private void hideOverviewRuler() { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.hideOverviewRuler(); } private boolean isOverviewRulerVisible() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(OVERVIEW_RULER); } private Color getColor(String key) { RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), key); return getColor(rgb); } private Color getColor(RGB rgb) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private Color getColor(AnnotationType annotationType) { AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType); if (info != null) return getColor(info.fColorPreference); return null; } /* * @see AbstractTextEditor#dispose() */ public void dispose() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter); if (fPropertyChangeListener != null) { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fJavaEditorErrorTickUpdater != null) { fJavaEditorErrorTickUpdater.dispose(); fJavaEditorErrorTickUpdater= null; } if (fSelectionHistory != null) fSelectionHistory.dispose(); stopBracketHighlighting(); stopLineHighlighting(); if (fPaintManager != null) { fPaintManager.dispose(); fPaintManager= null; } if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } /* * @see AbstractTextEditor#createPartControl(Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); fPaintManager= new PaintManager(getSourceViewer()); if (isBracketHighlightingEnabled()) startBracketHighlighting(); if (isLineHighlightingEnabled()) startLineHighlighting(); if (isPrintMarginVisible()) showPrintMargin(); Iterator e= ANNOTATION_MAP.keySet().iterator(); while (e.hasNext()) { AnnotationType type= (AnnotationType) e.next(); if (isAnnotationIndicationEnabled(type)) startAnnotationIndication(type); } if (isTabConversionEnabled()) startTabConversion(); if (isOverviewRulerVisible()) showOverviewRuler(); Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(fPropertyChangeListener); IPreferenceStore preferenceStore= getPreferenceStore(); boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS); boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS); fBracketInserter.setCloseBracketsEnabled(closeBrackets); fBracketInserter.setCloseStringsEnabled(closeStrings); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter); } private static char getPeerCharacter(char character) { switch (character) { case '(': return ')'; case ')': return '('; case '[': return ']'; case ']': return '['; case '"': return character; default: throw new IllegalArgumentException(); } } private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { final char fExitCharacter; public ExitPolicy(char exitCharacter) { fExitCharacter= exitCharacter; } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (manager.anyPositionIncludes(offset, length)) return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false); else return new ExitFlags(LinkedPositionUI.COMMIT, true); } switch (event.character) { case '\b': if (manager.getFirstPosition().length == 0) return new ExitFlags(0, false); else return null; case '\n': case '\r': return new ExitFlags(LinkedPositionUI.COMMIT, true); default: return null; } } } private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener { private boolean fCloseBrackets= true; private boolean fCloseStrings= true; private int fOffset; private int fLength; public void setCloseBracketsEnabled(boolean enabled) { fCloseBrackets= enabled; } public void setCloseStringsEnabled(boolean enabled) { fCloseStrings= enabled; } private boolean isResfOfLineEmpty(IDocument document, int offset) { if (offset == document.getLength()) return true; try { IRegion line= document.getLineInformationOfOffset(offset); String string= document.get(offset, line.getOffset() + line.getLength() - offset); for (int i= 0; i < string.length(); i++) if (!Character.isWhitespace(string.charAt(i))) return false; return true; } catch (BadLocationException e) { return true; } } /* * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ public void verifyKey(VerifyEvent event) { if (!event.doit) return; final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); final Point selection= sourceViewer.getSelectedRange(); final int offset= selection.x; final int length= selection.y; switch (event.character) { case '(': case '[': if (!fCloseBrackets || !isResfOfLineEmpty(document, offset + length)) return; case '"': if (event.character == '"' && !fCloseStrings) return; try { ITypedRegion partition= document.getPartition(offset); if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset) return; final char character= event.character; final char closingCharacter= getPeerCharacter(character); final StringBuffer buffer= new StringBuffer(); buffer.append(character); buffer.append(closingCharacter); document.replace(offset, length, buffer.toString()); LinkedPositionManager manager= new LinkedPositionManager(document); manager.addPosition(offset + 1, 0); fOffset= offset; fLength= 2; LinkedPositionUI editor= new LinkedPositionUI(sourceViewer, manager); editor.setCancelListener(this); editor.setExitPolicy(new ExitPolicy(closingCharacter)); editor.setFinalCaretOffset(offset + 2); editor.enter(); IRegion newSelection= editor.getSelectedRegion(); sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength()); event.doit= false; } catch (BadLocationException e) { } break; } } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean) */ public void exit(boolean accept) { if (accept) return; // remove brackets try { final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); document.replace(fOffset, fLength, null); } catch (BadLocationException e) { } } } protected AnnotationType getAnnotationType(String preferenceKey) { Iterator e= ANNOTATION_MAP.keySet().iterator(); while (e.hasNext()) { AnnotationType type= (AnnotationType) e.next(); AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type); if (info != null) { if (preferenceKey.equals(info.fColorPreference) || preferenceKey.equals(info.fEditorPreference) || preferenceKey.equals(info.fOverviewRulerPreference)) return type; } } return null; } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CLOSE_BRACKETS.equals(p)) { fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p)); return; } if (CLOSE_STRINGS.equals(p)) { fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p)); return; } if (SPACES_FOR_TABS.equals(p)) { if (isTabConversionEnabled()) startTabConversion(); else stopTabConversion(); return; } if (MATCHING_BRACKETS.equals(p)) { if (isBracketHighlightingEnabled()) startBracketHighlighting(); else stopBracketHighlighting(); return; } if (MATCHING_BRACKETS_COLOR.equals(p)) { if (fBracketPainter != null) fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); return; } if (CURRENT_LINE.equals(p)) { if (isLineHighlightingEnabled()) startLineHighlighting(); else stopLineHighlighting(); return; } if (CURRENT_LINE_COLOR.equals(p)) { if (fLinePainter != null) { stopLineHighlighting(); startLineHighlighting(); } return; } if (PRINT_MARGIN.equals(p)) { if (isPrintMarginVisible()) showPrintMargin(); else hidePrintMargin(); return; } if (PRINT_MARGIN_COLOR.equals(p)) { if (fPrintMarginPainter != null) fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); return; } if (PRINT_MARGIN_COLUMN.equals(p)) { if (fPrintMarginPainter != null) fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); return; } if (OVERVIEW_RULER.equals(p)) { if (isOverviewRulerVisible()) showOverviewRuler(); else hideOverviewRuler(); return; } AnnotationType type= getAnnotationType(p); if (type != null) { AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type); if (info.fColorPreference.equals(p)) { Color color= getColor(type); if (fProblemPainter != null) { fProblemPainter.setColor(type, color); fProblemPainter.paint(IPainter.CONFIGURATION); } setColorInOverviewRuler(type, color); return; } if (info.fEditorPreference.equals(p)) { if (isAnnotationIndicationEnabled(type)) startAnnotationIndication(type); else stopAnnotationIndication(type); return; } if (info.fOverviewRulerPreference.equals(p)) { if (isAnnotationIndicationInOverviewRulerEnabled(type)) showAnnotationIndicationInOverviewRuler(type, true); else showAnnotationIndicationInOverviewRuler(type, false); return; } } IContentAssistant c= asv.getContentAssistant(); if (c instanceof ContentAssistant) ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event); } } finally { super.handlePreferenceStoreChanged(event); } } /** * Handles a property change event describing a change * of the java core's preferences and updates the preference * related editor properties. * * @param event the property change event */ protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CODE_FORMATTER_TAB_SIZE.equals(p)) { asv.updateIndentationPrefixes(); if (fTabConverter != null) fTabConverter.setNumberOfSpacesPerTab(getTabSize()); } } } /* * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { String p= event.getProperty(); boolean affects=MATCHING_BRACKETS_COLOR.equals(p) || CURRENT_LINE_COLOR.equals(p) || ERROR_INDICATION_COLOR.equals(p) || WARNING_INDICATION_COLOR.equals(p) || TASK_INDICATION_COLOR.equals(p); return affects ? affects : super.affectsTextPresentation(event); } /* * @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return new AdaptedSourceViewer(parent, ruler, styles); } /* * @see JavaEditor#synchronizeOutlinePageSelection() */ public void synchronizeOutlinePageSelection() { if (isEditingScriptRunning()) return; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null || fOutlinePage == null) return; StyledText styledText= sourceViewer.getTextWidget(); if (styledText == null) return; int offset= sourceViewer.getVisibleRegion().getOffset(); int caret= offset + styledText.getCaretOffset(); IJavaElement element= getElementAt(caret, false); ISourceReference reference= getSourceReference(element, caret); if (reference != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select(reference); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } } private ISourceReference getSourceReference(IJavaElement element, int offset) { if ( !(element instanceof ISourceReference)) return null; if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { IImportDeclaration declaration= (IImportDeclaration) element; IImportContainer container= (IImportContainer) declaration.getParent(); ISourceRange srcRange= null; try { srcRange= container.getSourceRange(); } catch (JavaModelException e) { } if (srcRange != null && srcRange.getOffset() == offset) return container; } return (ISourceReference) element; } /* * @see IReconcilingParticipant#reconciled() */ public void reconciled() { if (!JavaEditorPreferencePage.synchronizeOutlineOnCursorMove()) { Shell shell= getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(new Runnable() { public void run() { synchronizeOutlinePageSelection(); } }); } } } protected void updateStateDependentActions() { super.updateStateDependentActions(); fGenerateActionGroup.editorStateChanged(); } /** * Returns the updated java element for the old java element. */ private IJavaElement findElement(IJavaElement element) { if (element == null) return null; IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { synchronized (unit) { unit.reconcile(); } IJavaElement[] findings= unit.findElements(element); if (findings != null && findings.length > 0) return findings[0]; } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /** * Returns the offset of the given Java element. */ private int getOffset(IJavaElement element) { if (element instanceof ISourceReference) { ISourceReference sr= (ISourceReference) element; try { ISourceRange srcRange= sr.getSourceRange(); if (srcRange != null) return srcRange.getOffset(); } catch (JavaModelException e) { } } return -1; } /* * @see AbstractTextEditor#rememberSelection() */ protected void rememberSelection() { ISelectionProvider sp= getSelectionProvider(); fRememberedSelection= (sp == null ? null : (ITextSelection) sp.getSelection()); if (fRememberedSelection != null) { fRememberedElement= getElementAt(fRememberedSelection.getOffset(), true); fRememberedElementOffset= getOffset(fRememberedElement); } } /* * @see AbstractTextEditor#restoreSelection() */ protected void restoreSelection() { try { if (getSourceViewer() == null || fRememberedSelection == null) return; IJavaElement newElement= findElement(fRememberedElement); int newOffset= getOffset(newElement); int offset= (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - fRememberedElementOffset : 0; selectAndReveal(offset + fRememberedSelection.getOffset(), fRememberedSelection.getLength()); } finally { fRememberedSelection= null; fRememberedElement= null; fRememberedElementOffset= -1; } } /* * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) */ protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { String oldExtension= ""; //$NON-NLS-1$ if (originalElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) originalElement).getFile(); if (file != null) { String ext= file.getFileExtension(); if (ext != null) oldExtension= ext; } } String newExtension= ""; //$NON-NLS-1$ if (movedElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) movedElement).getFile(); if (file != null) newExtension= file.getFileExtension(); } return oldExtension.equals(newExtension); } }
25,900
Bug 25900 NPE in CompilationUnitEditor
Build I20021105++ - load JUnit - expand a CU - delete CU on disk - select a field of expanded CU - open type hierarchy ==> you get an editor saying that the file doesn't exist on disk - close editor java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.LinePainter.drawHighlightLine (LinePainter.java:110) at org.eclipse.jdt.internal.ui.javaeditor.LinePainter.deactivate (LinePainter.java:128) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.stopLineHighlightin g(CompilationUnitEditor.java:1142) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.dispose (CompilationUnitEditor.java:1350) at org.eclipse.ui.internal.WorkbenchPage$5.run(WorkbenchPage.java:910) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:839) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.WorkbenchPage.disposePart (WorkbenchPage.java:908) at org.eclipse.ui.internal.WorkbenchPage.closeEditor (WorkbenchPage.java:723) at org.eclipse.ui.internal.WorkbenchPage.closeEditor (WorkbenchPage.java:690) at org.eclipse.ui.internal.EditorPane.doHide(EditorPane.java:83) at org.eclipse.ui.internal.EditorWorkbook$1.itemClosed (EditorWorkbook.java:121) at org.eclipse.swt.custom.CTabFolder.closeNotify(CTabFolder.java:304) at org.eclipse.swt.custom.CTabFolder.access$13(CTabFolder.java:294) at org.eclipse.swt.custom.CTabFolder$4.handleEvent(CTabFolder.java:434) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1419) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1402) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24)
verified fixed
4618b77
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T15:04:55Z
2002-11-08T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/IPainter.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ public interface IPainter { /** Paint reasons */ int SELECTION= 0; int TEXT_CHANGE= 1; int KEY_STROKE= 2; int MOUSE_BUTTON= 4; int INTERNAL= 8; int CONFIGURATION= 16; void dispose(); void paint(int reason); void deactivate(boolean redraw); void setPositionManager(IPositionManager manager); }
25,830
Bug 25830 JUnit plugin does not run using JDK 1.1.8
Eclipse will allow you to specify JDK 1.1.8 a JRE for running code. This is quite useful for those developing code for environments that don't support Java 2, such as some browser VMs. However, the JUnit plugin does not work with the JDK 1.1.8 because the RemoteTestRunner uses classes that aren't available in that VM. When I create a simple JUnit test and attempt to run it in Eclipse using JDK 1.1.8, I get the following message in the console: java.lang.NoClassDefFoundError: java/util/ArrayList at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.<init> (RemoteTestRunner.java:32) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (RemoteTestRunner.java:149) I know the Vector class isn't as elegant as ArrayList, but it's available everywhere - could it be used instead, or perhaps an alternate JDK 1.1.8- friendly remote test runner could be invoked in such a scenario?
resolved fixed
8562a30
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-11T22:41:01Z
2002-11-07T14:40:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/runner/RemoteTestRunner.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.runner; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.Socket; import java.util.ArrayList; import java.util.List; import junit.extensions.TestDecorator; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestListener; import junit.framework.TestResult; import junit.framework.TestSuite; import org.eclipse.jdt.internal.junit.ui.JUnitMessages; /** * A TestRunner that reports results via a socket connection. * See MessageIds for more information about the protocl. */ public class RemoteTestRunner implements TestListener { /** * Holder for information for a rerun request */ private static class RerunRequest { String fClassName; String fTestName; public RerunRequest(String className, String testName) { fClassName= className; fTestName= testName; } } private static final String SUITE_METHODNAME= "suite"; //$NON-NLS-1$ /** * The name of the test classes to be executed */ private String[] fTestClassNames; /** * The current test result */ private TestResult fTestResult; /** * The client socket. */ private Socket fClientSocket; /** * Print writer for sending messages */ private PrintWriter fWriter; /** * Reader for incoming messages */ private BufferedReader fReader; /** * Host to connect to, default is the localhost */ private String fHost= ""; //$NON-NLS-1$ /** * Port to connect to. */ private int fPort= -1; /** * Is the debug mode enabled? */ private boolean fDebugMode= false; /** * Keep the test run server alive after a test run has finished. * This allows to rerun tests. */ private boolean fKeepAlive= false; /** * Has the server been stopped */ private boolean fStopped= false; /** * Queue of rerun requests. */ private List fRerunRequests= new ArrayList(10); /** * Reader thread that processes messages from the client. */ private class ReaderThread extends Thread { public ReaderThread() { super("ReaderThread"); //$NON-NLS-1$ } public void run(){ try { String message= null; while (true) { if ((message= fReader.readLine()) != null) { if (message.startsWith(MessageIds.TEST_STOP)){ fStopped= true; RemoteTestRunner.this.stop(); synchronized(RemoteTestRunner.this) { RemoteTestRunner.this.notifyAll(); } break; } else if (message.startsWith(MessageIds.TEST_RERUN)) { String arg= message.substring(MessageIds.MSG_HEADER_LENGTH); int c= arg.indexOf(" "); //$NON-NLS-1$ synchronized(RemoteTestRunner.this) { fRerunRequests.add(new RerunRequest(arg.substring(0, c), arg.substring(c+1))); RemoteTestRunner.this.notifyAll(); } } } } } catch (Exception e) { RemoteTestRunner.this.stop(); } } } /** * The main entry point. * Parameters<pre> * -classnames: the name of the test suite class * -host: the host to connect to - default local host * -port: the port to connect to, mandatory argument * -keepalive: keep the process alive after a test run * </pre> */ public static void main(String[] args) { RemoteTestRunner testRunServer= new RemoteTestRunner(); testRunServer.init(args); testRunServer.run(); // fix for 14434 System.exit(0); } /** * Parse command line arguments. Hook for subclasses to process * additional arguments. */ protected void init(String[] args) { defaultInit(args); } /** * The class loader to be used for loading tests. * Subclasses may override to use another class loader. */ protected ClassLoader getClassLoader() { return getClass().getClassLoader(); } /** * Process the default arguments. */ protected final void defaultInit(String[] args) { for(int i= 0; i < args.length; i++) { if(args[i].toLowerCase().equals("-classnames") || args[i].toLowerCase().equals("-classname")){ //$NON-NLS-1$ //$NON-NLS-2$ ArrayList list= new ArrayList(); for (int j= i+1; j < args.length; j++) { if (args[j].startsWith("-")) //$NON-NLS-1$ break; list.add(args[j]); } fTestClassNames= (String[]) list.toArray(new String[list.size()]); } else if(args[i].toLowerCase().equals("-testnamefile")) { String testNameFile= args[i+1]; try { readTestNames(testNameFile); } catch (IOException e) { throw new IllegalArgumentException("Cannot read testname file."); } i++; } else if(args[i].toLowerCase().equals("-port")) { //$NON-NLS-1$ fPort= Integer.parseInt(args[i+1]); i++; } else if(args[i].toLowerCase().equals("-host")) { //$NON-NLS-1$ fHost= args[i+1]; i++; } else if(args[i].toLowerCase().equals("-keepalive")) { //$NON-NLS-1$ fKeepAlive= true; } else if(args[i].toLowerCase().equals("-debugging") || args[i].toLowerCase().equals("-debug")){ //$NON-NLS-1$ //$NON-NLS-2$ fDebugMode= true; } } if(fTestClassNames == null || fTestClassNames.length == 0) throw new IllegalArgumentException(JUnitMessages.getString("RemoteTestRunner.error.classnamemissing")); //$NON-NLS-1$ if (fPort == -1) throw new IllegalArgumentException(JUnitMessages.getString("RemoteTestRunner.error.portmissing")); //$NON-NLS-1$ if (fDebugMode) System.out.println("keepalive "+fKeepAlive); //$NON-NLS-1$ } private void readTestNames(String testNameFile) throws IOException { BufferedReader br= new BufferedReader(new FileReader(new File(testNameFile))); try { String line; ArrayList list= new ArrayList(); while ((line= br.readLine()) != null) { list.add(line); } fTestClassNames= (String[]) list.toArray(new String[list.size()]); } finally { br.close(); } if (fDebugMode) { System.out.println("Tests:"); for (int i= 0; i < fTestClassNames.length; i++) { System.out.println(" "+fTestClassNames[i]); } } } /** * Connects to the remote ports and runs the tests. */ protected void run() { if (!connect()) { return; } fTestResult= new TestResult(); fTestResult.addListener(this); runTests(fTestClassNames); fTestResult.removeListener(this); if (fTestResult != null) { fTestResult.stop(); fTestResult= null; } if (fKeepAlive) waitForReruns(); shutDown(); } /** * Waits for rerun requests until an explicit stop request */ private synchronized void waitForReruns() { while (!fStopped) { try { wait(); if (!fStopped && fRerunRequests.size() > 0) { RerunRequest r= (RerunRequest)fRerunRequests.remove(0); rerunTest(r.fClassName, r.fTestName); } } catch (InterruptedException e) { } } } /** * Returns the Test corresponding to the given suite. */ private Test getTest(String suiteClassName) { Class testClass= null; try { testClass= loadSuiteClass(suiteClassName); } catch (ClassNotFoundException e) { String clazz= e.getMessage(); if (clazz == null) clazz= suiteClassName; runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.classnotfound", clazz)); //$NON-NLS-1$ return null; } catch(Exception e) { runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.exception", e.toString() )); //$NON-NLS-1$ return null; } Method suiteMethod= null; try { suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]); } catch(Exception e) { // try to extract a test suite automatically return new TestSuite(testClass); } Test test= null; try { test= (Test)suiteMethod.invoke(null, new Class[0]); // static method } catch (InvocationTargetException e) { runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.invoke", e.getTargetException().toString() )); //$NON-NLS-1$ return null; } catch (IllegalAccessException e) { runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.invoke", e.toString() )); //$NON-NLS-1$ return null; } return test; } protected void runFailed(String message) { System.err.println(message); } /** * Loads the test suite class. */ private Class loadSuiteClass(String className) throws ClassNotFoundException { if (className == null) return null; return getClassLoader().loadClass(className); } /** * Runs a set of tests. */ private void runTests(String[] testClassNames) { // instantiate all tests Test[] suites= new Test[testClassNames.length]; for (int i= 0; i < suites.length; i++) { Test test= getTest(testClassNames[i]); suites[i]= test; } // count all testMethods and inform ITestRunListeners int count= countTests(suites); notifyTestRunStarted(count); if (count == 0) { notifyTestRunEnded(0); return; } long startTime= System.currentTimeMillis(); if (fDebugMode) System.out.print("start send tree..."); //$NON-NLS-1$ for (int i= 0; i < suites.length; i++) { sendTree(suites[i]); } if (fDebugMode) System.out.println("done send tree - time(ms): "+(System.currentTimeMillis()-startTime)); //$NON-NLS-1$ long testStartTime= System.currentTimeMillis(); for (int i= 0; i < suites.length; i++) { suites[i].run(fTestResult); } // inform ITestRunListeners of test end if (fTestResult == null || fTestResult.shouldStop()) notifyTestRunStopped(System.currentTimeMillis() - testStartTime); else notifyTestRunEnded(System.currentTimeMillis() - testStartTime); } private int countTests(Test[] tests) { int count= 0; for (int i= 0; i < tests.length; i++) { if (tests[i] != null) count= count + tests[i].countTestCases(); } return count; } /** * Reruns a test as defined by the fully qualified class name and * the name of the test. */ public void rerunTest(String className, String testName) { Test reloadedTest= null; try { Class reloadedTestClass= getClassLoader().loadClass(className); Class[] classArgs= { String.class }; Constructor constructor= null; try { constructor= reloadedTestClass.getConstructor(classArgs); reloadedTest= (Test)constructor.newInstance(new Object[]{testName}); } catch (NoSuchMethodException e) { // try the no arg constructor supported in 3.8.1 constructor= reloadedTestClass.getConstructor(new Class[0]); reloadedTest= (Test)constructor.newInstance(new Object[0]); if (reloadedTest instanceof TestCase) ((TestCase) reloadedTest).setName(testName); } } catch(Exception e) { runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.load", testName )); //$NON-NLS-1$ e.printStackTrace(); return; } TestResult result= new TestResult(); reloadedTest.run(result); notifyTestReran(result, className, testName); } /* * @see TestListener#addError(Test, Throwable) */ public final void addError(Test test, Throwable throwable) { notifyTestFailed(MessageIds.TEST_ERROR, test.toString(), getTrace(throwable)); } /* * @see TestListener#addFailure(Test, AssertionFailedError) */ public final void addFailure(Test test, AssertionFailedError assertionFailedError) { notifyTestFailed(MessageIds.TEST_FAILED, test.toString(), getTrace(assertionFailedError)); } /* * @see TestListener#endTest(Test) */ public void endTest(Test test) { notifyTestEnded(test.toString()); } /* * @see TestListener#startTest(Test) */ public void startTest(Test test) { notifyTestStarted(test.toString()); } private void sendTree(Test test){ if(test instanceof TestDecorator){ TestDecorator decorator= (TestDecorator) test; sendTree(decorator.getTest()); } else if(test instanceof TestSuite){ TestSuite suite= (TestSuite) test; notifyTestTreeEntry(suite.toString().trim() + ',' + true + ',' + suite.testCount()); for(int i=0; i < suite.testCount(); i++){ sendTree(suite.testAt(i)); } } else { notifyTestTreeEntry(test.toString().trim() + ',' + false + ',' + test.countTestCases()); } } /** * Returns the stack trace for the given throwable. */ private String getTrace(Throwable t) { StringWriter stringWriter= new StringWriter(); PrintWriter writer= new PrintWriter(stringWriter); t.printStackTrace(writer); StringBuffer buffer= stringWriter.getBuffer(); return buffer.toString(); } /** * Stop the current test run. */ protected void stop() { if (fTestResult != null) { fTestResult.stop(); } } /** * Connect to the remote test listener. */ private boolean connect() { if (fDebugMode) System.out.println("RemoteTestRunner: trying to connect" + fHost + ":" + fPort); //$NON-NLS-1$ //$NON-NLS-2$ Exception exception= null; for (int i= 1; i < 10; i++) { try{ fClientSocket= new Socket(fHost, fPort); fWriter= new PrintWriter(fClientSocket.getOutputStream(), false/*true*/); fReader= new BufferedReader(new InputStreamReader(fClientSocket.getInputStream())); new ReaderThread().start(); return true; } catch(IOException e){ exception= e; } try { Thread.sleep(2000); } catch(InterruptedException e) { } } runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.connect", new String[]{fHost, Integer.toString(fPort)} )); //$NON-NLS-1$ exception.printStackTrace(); return false; } /** * Shutsdown the connection to the remote test listener. */ private void shutDown() { if (fWriter != null) { fWriter.close(); fWriter= null; } try { if (fReader != null) { fReader.close(); fReader= null; } } catch(IOException e) { if (fDebugMode) e.printStackTrace(); } try { if (fClientSocket != null) { fClientSocket.close(); fClientSocket= null; } } catch(IOException e) { if (fDebugMode) e.printStackTrace(); } } private void sendMessage(String msg) { if(fWriter == null) return; fWriter.println(msg); } private void notifyTestRunStarted(int testCount) { sendMessage(MessageIds.TEST_RUN_START + testCount); } private void notifyTestRunEnded(long elapsedTime) { sendMessage(MessageIds.TEST_RUN_END + elapsedTime); fWriter.flush(); //shutDown(); } private void notifyTestRunStopped(long elapsedTime) { sendMessage(MessageIds.TEST_STOPPED + elapsedTime ); fWriter.flush(); //shutDown(); } private void notifyTestStarted(String testName) { sendMessage(MessageIds.TEST_START + testName); fWriter.flush(); } private void notifyTestEnded(String testName) { sendMessage(MessageIds.TEST_END + testName); } private void notifyTestFailed(String status, String testName, String trace) { sendMessage(status + testName); sendMessage(MessageIds.TRACE_START); sendMessage(trace); sendMessage(MessageIds.TRACE_END); fWriter.flush(); } private void notifyTestTreeEntry(String treeEntry) { sendMessage(MessageIds.TEST_TREE + treeEntry); } private void notifyTestReran(TestResult result, String testClass, String testName) { TestFailure failure= null; if (result.errorCount() > 0) { failure= (TestFailure)result.errors().nextElement(); } if (result.failureCount() > 0) { failure= (TestFailure)result.failures().nextElement(); } if (failure != null) { Throwable t= failure.thrownException(); String trace= getTrace(t); sendMessage(MessageIds.RTRACE_START); sendMessage(trace); sendMessage(MessageIds.RTRACE_END); fWriter.flush(); } String status= "OK"; //$NON-NLS-1$ if (result.errorCount() > 0) status= "ERROR"; //$NON-NLS-1$ else if (result.failureCount() > 0) status= "FAILURE"; //$NON-NLS-1$ if (fPort != -1) { sendMessage(MessageIds.TEST_RERAN + testClass+" "+testName+" "+status); //$NON-NLS-1$ //$NON-NLS-2$ fWriter.flush(); } } }
25,870
Bug 25870 Code assist for comments doesn't add new line character.
Eclipse's code assist for comment and javadoc doesn't add a line feed character to the second line of comment, it adds only carriage return character. Since other editors do not treat carriage return itself as a line feed, line nubmers for the source will appear differently between eclipse and other editors. HOW TO REPRODUCE: 1. In java file, type /** then press enter. eclipse will add the following to the source. /** * comment */ 2. Open this file with a different editor: vi, emacs, etc. You will see your comment looking like this instead... /** * comment */ 3. line number for your source after this comment will appear differently between eclipse editor and any other editor.
resolved fixed
ca33a59
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-12T09:15:34Z
2002-11-08T01:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java
package org.eclipse.jdt.internal.ui.text.javadoc; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.text.BreakIterator; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationMessages; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; /** * Auto indent strategy for java doc comments */ public class JavaDocAutoIndentStrategy extends DefaultAutoIndentStrategy { public JavaDocAutoIndentStrategy() { } /** * Returns whether the text ends with one of the given search strings. */ private boolean endsWithDelimiter(IDocument d, String txt) { String[] delimiters= d.getLegalLineDelimiters(); for (int i= 0; i < delimiters.length; i++) { if (txt.endsWith(delimiters[i])) return true; } return false; } /** * Copies the indentation of the previous line and add a star. * If the javadoc just started on this line add standard method tags * and close the javadoc. * * @param d the document to work on * @param c the command to deal with */ private void jdocIndentAfterNewLine(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { // find start of line int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); IRegion info= d.getLineInformationOfOffset(p); int start= info.getOffset(); // find white spaces int end= findEndOfWhiteSpace(d, start, c.offset); StringBuffer buf= new StringBuffer(c.text); if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness not work for class comments // append to input String indentation= jdocExtractLinePrefix(d, d.getLineOfOffset(c.offset)); buf.append(indentation); if (end < c.offset) { if (d.getChar(end) == '/') { // javadoc started on this line buf.append(" * "); //$NON-NLS-1$ if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(CompilationUnitEditor.CLOSE_JAVADOCS) && isNewComment(d, c.offset)) { String lineDelimiter= d.getLegalLineDelimiters()[0]; c.doit= false; d.replace(c.offset, 0, lineDelimiter + indentation + " */"); //$NON-NLS-1$ // evaluate method signature ICompilationUnit unit= getCompilationUnit(); if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(CompilationUnitEditor.ADD_JAVADOC_TAGS) && unit != null) { try { unit.reconcile(); String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit); if (string != null) d.replace(c.offset, 0, string); } catch (CoreException e) { // ignore } } } } } } c.text= buf.toString(); } catch (BadLocationException excp) { // stop work } } private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit) throws CoreException, BadLocationException { IJavaElement element= unit.getElementAt(command.offset); if (element == null) return null; switch (element.getElementType()) { case IJavaElement.TYPE: return createTypeTags(document, command, indentation, lineDelimiter, (IType) element); case IJavaElement.METHOD: return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element); default: return null; } } private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IType type) throws CoreException, BadLocationException { Template[] templates= Templates.getInstance().getTemplates(); String comment= null; for (int i= 0; i < templates.length; i++) { if ("typecomment".equals(templates[i].getName())) { //$NON-NLS-1$ comment= JavaContext.evaluateTemplate(templates[i], type.getCompilationUnit(), type.getSourceRange().getOffset()); break; } } // trim comment start and end if any if (comment != null) { comment= comment.trim(); if (comment.endsWith("*/")) //$NON-NLS-1$ comment= comment.substring(0, comment.length() - 2); comment= comment.trim(); if (comment.startsWith("/**")) //$NON-NLS-1$ comment= comment.substring(3); } return (comment == null || comment.length() == 0) ? CodeGenerationMessages.getString("AddJavaDocStubOperation.configure.message") //$NON-NLS-1$ : comment; } private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method) throws BadLocationException, JavaModelException { IRegion partition= document.getPartition(command.offset); ISourceRange sourceRange= method.getSourceRange(); if (sourceRange == null || sourceRange.getOffset() != partition.getOffset()) return null; boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$ IMethod inheritedMethod= getInheritedMethod(method); if (inheritedMethod == null) { if (isJavaDoc) return createJavaDocMethodTags(method, lineDelimiter + indentation, ""); //$NON-NLS-1$ } else { if (isJavaDoc || JavaPreferencesSettings.getCodeGenerationSettings().createNonJavadocComments) return createJavaDocInheritedMethodTags(inheritedMethod, lineDelimiter + indentation, ""); //$NON-NLS-1$ } return null; } /** * Returns the method inherited from, <code>null</code> if method is newly defined. */ private static IMethod getInheritedMethod(IMethod method) throws JavaModelException { IType declaringType= method.getDeclaringType(); ITypeHierarchy typeHierarchy= declaringType.newSupertypeHierarchy(null); return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, declaringType, method.getElementName(), method.getParameterTypes(), method.isConstructor()); } protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) { if (c.offset < 2 || d.getLength() == 0) { return; } try { if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$ // modify document command c.length++; c.offset--; } } catch (BadLocationException excp) { // stop work } } /** * Guesses if the command operates within a newly created javadoc comment or not. * If in doubt, it will assume that the javadoc is new. */ private static boolean isNewComment(IDocument document, int commandOffset) { try { int lineIndex= document.getLineOfOffset(commandOffset) + 1; if (lineIndex >= document.getNumberOfLines()) return true; IRegion line= document.getLineInformation(lineIndex); ITypedRegion partition= document.getPartition(commandOffset); if (document.getLineOffset(lineIndex) >= partition.getOffset() + partition.getLength()) return true; String string= document.get(line.getOffset(), line.getLength()); if (!string.trim().startsWith("*")) //$NON-NLS-1$ return true; return false; } catch (BadLocationException e) { return false; } } /* * @see IAutoIndentStrategy#customizeDocumentCommand */ public void customizeDocumentCommand(IDocument document, DocumentCommand command) { try { ITypedRegion partition= document.getPartition(command.offset); int partitionStart= partition.getOffset(); int partitionEnd= partition.getLength() + partitionStart; String text= command.text; int offset= command.offset; int length= command.length; // partition change final int PREFIX_LENGTH= "/**".length(); //$NON-NLS-1$ final int POSTFIX_LENGTH= "*/".length(); //$NON-NLS-1$ if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd - POSTFIX_LENGTH) || text != null && text.length() >= 2 && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$ return; if (command.text != null && command.length == 0 && endsWithDelimiter(document, command.text)) jdocIndentAfterNewLine(document, command); else if (command.text != null && command.text.equals("/")) //$NON-NLS-1$ jdocIndentForCommentEnd(document, command); else if (command.text == null || command.text.length() == 0) jdocHandleBackspaceDelete(document, command); else if (command.text != null && command.length == 0 && command.text.length() > 0) jdocWrapParagraphOnInsert(document, command); } catch (BadLocationException e) { } } private void flushCommand(IDocument document, DocumentCommand command) throws BadLocationException { if (!command.doit) return; document.replace(command.offset, command.length, command.text); command.doit= false; if (command.text != null) command.offset += command.text.length(); command.length= 0; command.text= null; } protected void jdocWrapParagraphOnInsert(IDocument document, DocumentCommand command) throws BadLocationException { Assert.isTrue(command.length == 0); Assert.isTrue(command.text != null && command.text.length() == 1); if (!getPreferenceStore().getBoolean(CompilationUnitEditor.FORMAT_JAVADOCS)) return; int line= document.getLineOfOffset(command.offset); IRegion region= document.getLineInformation(line); int lineOffset= region.getOffset(); int lineLength= region.getLength(); String lineContents= document.get(lineOffset, lineLength); StringBuffer buffer= new StringBuffer(lineContents); int start= command.offset - lineOffset; int end= command.length + start; buffer.replace(start, end, command.text); // handle whitespace if (command.text != null && command.text.length() != 0 && command.text.trim().length() == 0) { String endOfLine= document.get(command.offset, lineOffset + lineLength - command.offset); // end of line if (endOfLine.length() == 0) { // move caret to next line flushCommand(document, command); if (isLineTooShort(document, line)) { int[] caretOffset= {command.offset}; jdocWrapParagraphFromLine(document, line, caretOffset, false); command.offset= caretOffset[0]; return; } // move caret to next line if possible if (line < document.getNumberOfLines() - 1 && isJavaDocLine(document, line + 1)) { String lineDelimiter= document.getLineDelimiter(line); String nextLinePrefix= jdocExtractLinePrefix(document, line + 1); command.offset += lineDelimiter.length() + nextLinePrefix.length(); } return; // inside whitespace at end of line } else if (endOfLine.trim().length() == 0) { // simply insert space return; } } // change in prefix region String prefix= jdocExtractLinePrefix(document, line); boolean wrapAlways= command.offset >= lineOffset && command.offset <= lineOffset + prefix.length(); // must insert the text now because it may include whitepace flushCommand(document, command); if (wrapAlways || calculateDisplayedWidth(buffer.toString()) > getMargin() || isLineTooShort(document, line)) { int[] caretOffset= {command.offset}; jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways); if (!wrapAlways) command.offset= caretOffset[0]; } } private static String trim(String string, boolean trimBegin, boolean trimEnd) { if (!trimBegin && !trimEnd) return string; if (trimBegin && trimEnd) return string.trim(); final int length= string.length(); if (trimBegin) { int i= 0; while (i < length && Character.isWhitespace(string.charAt(i))) i++; return string.substring(i); } else { int i= length; while (i > 0 && Character.isWhitespace(string.charAt(i - 1))) i--; return string.substring(0, i); } } /** * Method jdocWrapParagraphFromLine. * * @param document * @param line * @param always */ private void jdocWrapParagraphFromLine(IDocument document, int line, int[] caretOffset, boolean always) throws BadLocationException { String indent= jdocExtractLinePrefix(document, line); if (!always) { if (!indent.trim().startsWith("*")) //$NON-NLS-1$ return; if (indent.trim().startsWith("*/")) //$NON-NLS-1$ return; if (!isLineTooLong(document, line) && !isLineTooShort(document, line)) return; } int caret= caretOffset[0]; int caretLine= document.getLineOfOffset(caret); int lineOffset= document.getLineOffset(line); int paragraphOffset= lineOffset + indent.length(); caret -= paragraphOffset; StringBuffer buffer= new StringBuffer(); int currentLine= line; while (line == currentLine || isJavaDocLine(document, currentLine)) { if (buffer.length() != 0 && !Character.isWhitespace(buffer.charAt(buffer.length() - 1))) { buffer.append(' '); if (currentLine <= caretLine) ++caret; } String string= getLineContents(document, currentLine); buffer.append(string); currentLine++; } String paragraph= buffer.toString(); if (paragraph.trim().length() == 0) return; caretOffset[0]= caret; String delimiter= document.getLineDelimiter(0); String wrapped= formatParagraph(paragraph, caretOffset, indent, delimiter, getMargin()); int beginning= document.getLineOffset(line); int end= document.getLineOffset(currentLine); document.replace(beginning, end - beginning, wrapped.toString()); caretOffset[0] += beginning; } /** * Line break iterator to handle whitespaces as first class citizens. */ private static class LineBreakIterator { private final String fString; private final BreakIterator fIterator= BreakIterator.getLineInstance(); private int fStart; private int fEnd; private int fBufferedEnd; public LineBreakIterator(String string) { fString= string; fIterator.setText(string); } public int first() { fBufferedEnd= -1; fStart= fIterator.first(); return fStart; } public int next() { if (fBufferedEnd != -1) { fStart= fEnd; fEnd= fBufferedEnd; fBufferedEnd= -1; return fEnd; } fStart= fEnd; fEnd= fIterator.next(); if (fEnd == BreakIterator.DONE) return fEnd; final String string= fString.substring(fStart, fEnd); // whitespace if (string.trim().length() == 0) return fEnd; final String word= string.trim(); if (word.length() == string.length()) return fEnd; // suspected whitespace fBufferedEnd= fEnd; return fStart + word.length(); } }; /** * Formats a paragraph, using break iterator. * * @param offset an offset within the paragraph, which will be updated with respect to formatting. */ private static String formatParagraph(String paragraph, int[] offset, String prefix, String lineDelimiter, int margin) { LineBreakIterator iterator= new LineBreakIterator(paragraph); StringBuffer paragraphBuffer= new StringBuffer(); StringBuffer lineBuffer= new StringBuffer(); StringBuffer whiteSpaceBuffer= new StringBuffer(); int index= offset[0]; int indexBuffer= -1; for (int start= iterator.first(), end= iterator.next(); end != BreakIterator.DONE; start= end, end= iterator.next()) { String word= paragraph.substring(start, end); // word is whitespace if (word.trim().length() == 0) { whiteSpaceBuffer.append(word); // first word of line is always appended } else if (lineBuffer.length() == 0) { lineBuffer.append(prefix); lineBuffer.append(whiteSpaceBuffer.toString()); lineBuffer.append(word); } else { String line= lineBuffer.toString() + whiteSpaceBuffer.toString() + word.toString(); // margin exceeded if (calculateDisplayedWidth(line) > margin) { // flush line buffer and wrap paragraph paragraphBuffer.append(lineBuffer.toString()); paragraphBuffer.append(lineDelimiter); lineBuffer.setLength(0); lineBuffer.append(prefix); lineBuffer.append(word); // flush index buffer if (indexBuffer != -1) { offset[0]= indexBuffer; // correct for caret in whitespace at the end of line if (whiteSpaceBuffer.length() != 0 && index < start && index >= start - whiteSpaceBuffer.length()) offset[0] -= (index - (start - whiteSpaceBuffer.length())); indexBuffer= -1; } whiteSpaceBuffer.setLength(0); // margin not exceeded } else { lineBuffer.append(whiteSpaceBuffer.toString()); lineBuffer.append(word); whiteSpaceBuffer.setLength(0); } } if (index >= start && index < end) { indexBuffer= paragraphBuffer.length() + lineBuffer.length() + (index - start); if (word.trim().length() != 0) indexBuffer -= word.length(); } } // flush line buffer paragraphBuffer.append(lineBuffer.toString()); paragraphBuffer.append(lineDelimiter); // flush index buffer if (indexBuffer != -1) offset[0]= indexBuffer; // last position is not returned by break iterator else if (offset[0] == paragraph.length()) offset[0]= paragraphBuffer.length() - lineDelimiter.length(); return paragraphBuffer.toString(); } private static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /** * Returns the displayed width of a string, taking in account the displayed tab width. * The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string) { final int tabWidth= getPreferenceStore().getInt(JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH); int column= 0; for (int i= 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else column++; return column; } private String jdocExtractLinePrefix(IDocument d, int line) throws BadLocationException { IRegion region= d.getLineInformation(line); int lineOffset= region.getOffset(); int index= findEndOfWhiteSpace(d, lineOffset, lineOffset + d.getLineLength(line)); if (d.getChar(index) == '*') { index++; if (index != lineOffset + region.getLength() &&d.getChar(index) == ' ') index++; } return d.get(lineOffset, index - lineOffset); } private String getLineContents(IDocument d, int line) throws BadLocationException { int offset = d.getLineOffset(line); int length = d.getLineLength(line) - d.getLineDelimiter(line).length(); String lineContents = d.get(offset, length); int trim = jdocExtractLinePrefix(d, line).length(); return lineContents.substring(trim); } private static String getLine(IDocument document, int line) throws BadLocationException { IRegion region= document.getLineInformation(line); return document.get(region.getOffset(), region.getLength()); } /** * Returns <code>true</code> if the javadoc line is too short, <code>false</code> otherwise. */ private boolean isLineTooShort(IDocument document, int line) throws BadLocationException { if (!isJavaDocLine(document, line + 1)) return false; String nextLine= getLineContents(document, line + 1); if (nextLine.trim().length() == 0) return false; return true; } /** * Returns <code>true</code> if the line is too long, <code>false</code> otherwise. */ private boolean isLineTooLong(IDocument document, int line) throws BadLocationException { String lineContents= getLine(document, line); return calculateDisplayedWidth(lineContents) > getMargin(); } private static int getMargin() { return getPreferenceStore().getInt(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); } private static final String[] fgInlineTags= { "<b>", "<i>", "<em>", "<strong>", "<code>" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ }; private boolean isInlineTag(String string) { for (int i= 0; i < fgInlineTags.length; i++) if (string.startsWith(fgInlineTags[i])) return true; return false; } /** * returns true if the specified line is part of a paragraph and should be merged with * the previous line. */ private boolean isJavaDocLine(IDocument document, int line) throws BadLocationException { if (document.getNumberOfLines() < line) return false; int offset= document.getLineOffset(line); int length= document.getLineLength(line); int firstChar= findEndOfWhiteSpace(document, offset, offset + length); length -= firstChar - offset; String lineContents= document.get(firstChar, length); String prefix= lineContents.trim(); if (!prefix.startsWith("*") || prefix.startsWith("*/")) return false; lineContents= lineContents.substring(1).trim().toLowerCase(); // preserve empty lines if (lineContents.length() == 0) return false; // preserve @TAGS if (lineContents.startsWith("@")) //$NON-NLS-1$ return false; // preserve HTML tags which are not inline if (lineContents.startsWith("<") && !isInlineTag(lineContents)) return false; return true; } protected void jdocHandleBackspaceDelete(IDocument document, DocumentCommand c) { try { String text= document.get(c.offset, c.length); int line= document.getLineOfOffset(c.offset); int lineOffset= document.getLineOffset(line); // erase line delimiter if (document.getLineDelimiter(line).equals(text)) { String prefix= jdocExtractLinePrefix(document, line + 1); // strip prefix if any if (prefix.length() > 0) { int length= document.getLineDelimiter(line).length() + prefix.length(); document.replace(c.offset, length, null); c.doit= false; c.length= 0; return; } // backspace: beginning of a javadoc line } else if (document.getChar(c.offset - 1) == '*' && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset - lineOffset) { String prefix= jdocExtractLinePrefix(document, line); String lineDelimiter= document.getLineDelimiter(line - 1); int length= lineDelimiter.length() + prefix.length(); document.replace(c.offset - length + 1, length, null); c.doit= false; c.offset -= length - 1; c.length= 0; return; } else { document.replace(c.offset, c.length, null); c.doit= false; c.length= 0; } } catch (BadLocationException e) { JavaPlugin.log(e); } if (!getPreferenceStore().getBoolean(CompilationUnitEditor.FORMAT_JAVADOCS)) return; try { int line= document.getLineOfOffset(c.offset); int lineOffset= document.getLineOffset(line); String prefix= jdocExtractLinePrefix(document, line); boolean always= c.offset > lineOffset && c.offset <= lineOffset + prefix.length(); int[] caretOffset= {c.offset}; jdocWrapParagraphFromLine(document, document.getLineOfOffset(c.offset), caretOffset, always); c.offset= caretOffset[0]; } catch (BadLocationException e) { JavaPlugin.log(e); } } /** * Returns the compilation unit of the CompilationUnitEditor invoking the AutoIndentStrategy, * might return <code>null</code> on error. */ private static ICompilationUnit getCompilationUnit() { IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) return null; IWorkbenchPage page= window.getActivePage(); if (page == null) return null; IEditorPart editor= page.getActiveEditor(); if (editor == null) return null; IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(editor.getEditorInput()); if (unit == null) return null; return unit; } /** * Creates tags for a newly declared or defined method. */ private static String createJavaDocMethodTags(IMethod method, String preFix, String postFix) throws JavaModelException { final StringBuffer buffer= new StringBuffer(); final String[] parameterNames= method.getParameterNames(); for (int i= 0; i < parameterNames.length; i++) appendJavaDocLine(buffer, preFix, "param", parameterNames[i], postFix); //$NON-NLS-1$ final String returnType= method.getReturnType(); if (returnType != null && !returnType.equals(Signature.SIG_VOID)) { String name= Signature.getSimpleName(Signature.toString(returnType)); appendJavaDocLine(buffer, preFix, "return", name, postFix); //$NON-NLS-1$ } final String[] exceptionTypes= method.getExceptionTypes(); if (exceptionTypes != null) { for (int i= 0; i < exceptionTypes.length; i++) { String name= Signature.getSimpleName(Signature.toString(exceptionTypes[i])); appendJavaDocLine(buffer, preFix, "throws", name, postFix); //$NON-NLS-1$ } } return buffer.toString(); } /** * Creates tags for an inherited method. * * @param method the method it was inherited from. */ private static String createJavaDocInheritedMethodTags(IMethod method, String preFix, String postFix) throws JavaModelException { final StringBuffer buffer= new StringBuffer(); appendJavaDocLine(buffer, preFix, "see", createSeeTagLink(method), postFix); //$NON-NLS-1$ if (Flags.isDeprecated(method.getFlags())) appendJavaDocLine(buffer, preFix, "deprecated", "", postFix); //$NON-NLS-1$ //$NON-NLS-2$ return buffer.toString(); } /** * Creates a see tag link string of the form type#method(arguments). */ private static String createSeeTagLink(IMethod method) { final StringBuffer buffer= new StringBuffer(); buffer.append(JavaModelUtil.getFullyQualifiedName(method.getDeclaringType())); buffer.append('#'); buffer.append(method.getElementName()); buffer.append('('); String[] parameterTypes= method.getParameterTypes(); for (int i= 0; i < parameterTypes.length; i++) { if (i > 0) buffer.append(", "); //$NON-NLS-1$ buffer.append(Signature.getSimpleName(Signature.toString(parameterTypes[i]))); } buffer.append(')'); return buffer.toString(); } /** * Appends a single javadoc tag line to the string buffer. */ private static void appendJavaDocLine(StringBuffer buffer, String preFix, String token, String name, String postFix) { buffer.append(preFix); buffer.append(" * "); //$NON-NLS-1$ buffer.append('@'); buffer.append(token); buffer.append(' '); buffer.append(name); buffer.append(postFix); } }
25,737
Bug 25737 Control+PERIOD does not navigate to next warning
If my CU has only Warnings, Control+PERIOD does not work. Why is this? On the ? Toolbar it is labeled "Next Problem". I am trying to fix warnings indicated by JDT's compiler such as non-externalized strings, and by CheckStyle. This Action should still be enabled when there are warning in the CU.
verified fixed
4d5bc43
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-12T10:53:58Z
2002-11-05T18:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaMarkerAnnotation.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.util.Iterator; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugModelPresentation; import org.eclipse.search.ui.SearchUI; import org.eclipse.ui.IMarkerHelpRegistry; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.MarkerUtilities; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.internal.core.Util; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage; public class JavaMarkerAnnotation extends MarkerAnnotation implements IProblemAnnotation { private static Image fgImage; private static boolean fgImageInitialized= false; private IDebugModelPresentation fPresentation; private IProblemAnnotation fOverlay; private boolean fNotRelevant= false; private AnnotationType fType; public JavaMarkerAnnotation(IMarker marker) { super(marker); } /* * @see MarkerAnnotation#getUnknownImageName(IMarker) */ protected String getUnknownImageName(IMarker marker) { return JavaPluginImages.IMG_OBJS_GHOST; } /** * Initializes the annotation's icon representation and its drawing layer * based upon the properties of the underlying marker. */ protected void initialize() { IMarker marker= getMarker(); if (MarkerUtilities.isMarkerType(marker, IBreakpoint.BREAKPOINT_MARKER)) { if (fPresentation == null) fPresentation= DebugUITools.newDebugModelPresentation(); setLayer(4); setImage(fPresentation.getImage(marker)); fType= AnnotationType.UNKNOWN; } else { fType= AnnotationType.UNKNOWN; try { if (marker.isSubtypeOf(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER)) { int severity= marker.getAttribute(IMarker.SEVERITY, -1); switch (severity) { case IMarker.SEVERITY_ERROR: fType= AnnotationType.ERROR; break; case IMarker.SEVERITY_WARNING: fType= AnnotationType.WARNING; break; } } else if (marker.isSubtypeOf(IMarker.TASK)) fType= AnnotationType.TASK; else if (marker.isSubtypeOf(SearchUI.SEARCH_MARKER)) fType= AnnotationType.SEARCH_RESULT; else if (marker.isSubtypeOf(IMarker.BOOKMARK)) fType= AnnotationType.BOOKMARK; } catch(CoreException e) { JavaPlugin.log(e); } super.initialize(); if (JavaEditorPreferencePage.indicateQuixFixableProblems()) { IMarkerHelpRegistry registry= PlatformUI.getWorkbench().getMarkerHelpRegistry(); if (registry != null && registry.hasResolutions(marker)) { if (!fgImageInitialized) { fgImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM); fgImageInitialized= true; } setImage(fgImage); } } } } /* * @see IProblemAnnotation#getMessage() */ public String getMessage() { if (isProblem() || isTask()) return getMarker().getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } /* * @see IProblemAnnotation#isError() */ public boolean isError() { return fType == AnnotationType.ERROR; } /* * @see IProblemAnnotation#isWarning() */ public boolean isWarning() { return fType == AnnotationType.WARNING; } /* * @see IProblemAnnotation#isTemporary() */ public boolean isTemporary() { return false; } /* * @see IProblemAnnotation#getArguments() */ public String[] getArguments() { if (isProblem()) return Util.getProblemArgumentsFromMarker(getMarker().getAttribute(IJavaModelMarker.ARGUMENTS, "")); //$NON-NLS-1$ return null; } /* * @see IProblemAnnotation#getId() */ public int getId() { if (isProblem()) return getMarker().getAttribute(IJavaModelMarker.ID, -1); return -1; } /* * @see IProblemAnnotation#isProblem() */ public boolean isProblem() { return isWarning() || isError(); } /* * @see IProblemAnnotation#isTask() */ public boolean isTask() { return fType ==AnnotationType.TASK; } /* * @see IProblemAnnotation#isRelevant() */ public boolean isRelevant() { return !fNotRelevant; } public void setOverlay(IProblemAnnotation problemAnnotation) { if (fOverlay != null) fOverlay.removeOverlaid(this); fOverlay= problemAnnotation; fNotRelevant= (fNotRelevant || fOverlay != null); if (problemAnnotation != null) problemAnnotation.addOverlaid(this); } /* * @see IProblemAnnotation#hasOverlay() */ public boolean hasOverlay() { return fOverlay != null; } /* * @see MarkerAnnotation#getImage(Display) */ public Image getImage(Display display) { if (fOverlay != null) { Image image= fOverlay.getImage(display); if (image != null) return image; } return super.getImage(display); } /* * @see IProblemAnnotation#addOverlaid(IProblemAnnotation) */ public void addOverlaid(IProblemAnnotation annotation) { // not supported } /* * @see IProblemAnnotation#removeOverlaid(IProblemAnnotation) */ public void removeOverlaid(IProblemAnnotation annotation) { // not supported } /* * @see IProblemAnnotation#getOverlaidIterator() */ public Iterator getOverlaidIterator() { // not supported return null; } /* * @see org.eclipse.jdt.internal.ui.javaeditor.IProblemAnnotation#getAnnotationType() */ public AnnotationType getAnnotationType() { return fType; } }
26,019
Bug 26019 Deleting default package gives blank string in message
build I20021105 - in Package Explorer, select a default package - hit Delete - dialog box message is: Are you sure you want to delete ''? It should use the same text as shown in the view: Are you sure you want to delete '(default package)'?
verified fixed
2733ebc
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-12T10:55:53Z
2002-11-12T05:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/DeleteResourcesAction.java
package org.eclipse.jdt.internal.ui.reorg; import java.text.MessageFormat; import java.util.Iterator; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.DeleteResourceAction; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.actions.SelectionDispatchAction; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.refactoring.reorg.DeleteRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; public class DeleteResourcesAction extends SelectionDispatchAction { protected DeleteResourcesAction(IWorkbenchSite site) { super(site); } /* * @see SelectionDispatchAction#run(IStructuredSelection) */ protected void run(IStructuredSelection selection) { if (ClipboardActionUtil.hasOnlyProjects(selection)){ deleteProjects(selection); return; } DeleteRefactoring refactoring= new DeleteRefactoring(selection.toList()); if (!confirmDelete(selection)) return; if (hasReadOnlyResources(selection) && !isOkToDeleteReadOnly()) return; try{ if (! confirmDeleteSourceFolderAsSubresource(selection)) return; MultiStatus status= ClipboardActionUtil.perform(refactoring); if (!status.isOK()) { JavaPlugin.log(status); ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), ReorgMessages.getString("DeleteResourceAction.delete"), ReorgMessages.getString("DeleteResourceAction.exception"), status); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (CoreException e){ ExceptionHandler.handle(e, ReorgMessages.getString("DeleteResourceAction.delete"), ReorgMessages.getString("DeleteResourceAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$ return; } } private void deleteProjects(IStructuredSelection selection){ DeleteResourceAction action= new DeleteResourceAction(JavaPlugin.getActiveWorkbenchShell()); action.selectionChanged(selection); action.run(); } private static boolean isOkToDeleteReadOnly(){ String msg= ReorgMessages.getString("deleteAction.confirmReadOnly"); //$NON-NLS-1$ String title= ReorgMessages.getString("deleteAction.checkDeletion"); //$NON-NLS-1$ return MessageDialog.openQuestion( JavaPlugin.getActiveWorkbenchShell(), title, msg); } private boolean hasReadOnlyResources(IStructuredSelection selection){ for (Iterator iter= selection.iterator(); iter.hasNext();){ if (ReorgUtils.shouldConfirmReadOnly(iter.next())) return true; } return false; } private static boolean confirmDeleteSourceFolderAsSubresource(IStructuredSelection selection) throws CoreException { if (! containsSourceFolderAsSubresource(selection)) return true; String title= ReorgMessages.getString("deleteAction.confirm.title"); //$NON-NLS-1$ String label= ReorgMessages.getString("DeleteResourcesAction.deleteAction.confirm.message"); //$NON-NLS-1$ return MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, label); } private static boolean containsSourceFolderAsSubresource(IStructuredSelection selection) throws CoreException{ for (Iterator iter= selection.iterator(); iter.hasNext();){ Object each= iter.next(); if (each instanceof IFolder && containsSourceFolder((IFolder)each)) return true; } return false; } private static boolean containsSourceFolder(IFolder folder) throws CoreException{ IResource[] subFolders= folder.members(); for (int i = 0; i < subFolders.length; i++) { if (! (subFolders[i] instanceof IFolder)) continue; IJavaElement element= JavaCore.create((IFolder)folder); if (element instanceof IPackageFragmentRoot) return true; if (element instanceof IPackageFragment) continue; if (containsSourceFolder((IFolder)subFolders[i])) return true; } return false; } /* * @see SelectionDispatchAction#selectionChanged(IStructuredSelection) */ protected void selectionChanged(IStructuredSelection selection) { setEnabled(ClipboardActionUtil.canActivate(new DeleteRefactoring(selection.toList()))); } private static boolean confirmDelete(IStructuredSelection selection) { Assert.isTrue(ClipboardActionUtil.getSelectedProjects(selection).isEmpty()); String title= ReorgMessages.getString("deleteAction.confirm.title"); //$NON-NLS-1$ String label; if (selection.size() == 1){ String pattern= "Are you sure you want to delete ''{0}''?"; label= MessageFormat.format(pattern, new String[]{ReorgUtils.getName(selection.getFirstElement())}); } else { String pattern= "Are you sure you want to delete these {0} resources?"; label= MessageFormat.format(pattern, new String[]{String.valueOf(selection.size())}); } return MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, label); } }
25,137
Bug 25137 Paste enabled with deleted file on clipboard [ccp]
null
verified fixed
943bf11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-13T15:22:56Z
2002-10-21T19:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/PasteResourcesFromClipboardAction.java
package org.eclipse.jdt.internal.ui.reorg; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.CopyFilesAndFoldersOperation; import org.eclipse.ui.actions.CopyProjectAction; import org.eclipse.ui.part.ResourceTransfer; 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.JavaModelException; import org.eclipse.jdt.ui.actions.SelectionDispatchAction; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; public class PasteResourcesFromClipboardAction extends SelectionDispatchAction { private Clipboard fClipboard; protected PasteResourcesFromClipboardAction(IWorkbenchSite site, Clipboard clipboard) { super(site); Assert.isNotNull(clipboard); fClipboard= clipboard; } /* * @see SelectionDispatchAction#selectionChanged(IStructuredSelection) */ protected void selectionChanged(IStructuredSelection selection) { setEnabled(canOperateOn(selection)); } /* * @see SelectionDispatchAction#run(IStructuredSelection) */ public void run(IStructuredSelection selection) { IResource[] resourceData = getClipboardResources(); if (resourceData == null || resourceData.length == 0){ if (canPasteFiles(selection)) pasteFiles(selection.getFirstElement()); return; } pasteResources(selection, resourceData); } private void pasteFiles(Object target) { String[] fileData= getClipboardFiles(); if (fileData == null) return; IContainer container= convertToContainer(target); if (container == null) return; new CopyFilesAndFoldersOperation(getShell()).copyFiles(fileData, container); } private IContainer convertToContainer(Object target){ if (target instanceof IContainer) return (IContainer)target; try { return (IContainer)((IJavaElement)target).getCorrespondingResource(); } catch (JavaModelException e) { ExceptionHandler.handle(e, ReorgMessages.getString("PasteResourcesFromClipboardAction.error.title"), ReorgMessages.getString("PasteResourcesFromClipboardAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ return null; } } private void pasteResources(IStructuredSelection selection, IResource[] resourceData) { if (resourceData[0].getType() == IResource.PROJECT) pasteProject((IProject) resourceData[0]); else ReorgActionFactory.createDnDCopyAction(resourceData, getFirstSelectedResource(selection)).run(); } private void pasteProject(IProject project){ CopyProjectAction cpa= new CopyProjectAction(getShell()); cpa.selectionChanged(new StructuredSelection(project)); if (! cpa.isEnabled()) return; cpa.run(); } //- enablement --- private boolean canOperateOn(IStructuredSelection selection){ IResource[] resourceData= getClipboardResources(); if (resourceData == null || resourceData.length == 0) return canPasteFiles(selection); if (ClipboardActionUtil.isOneOpenProject(resourceData)) return true; if (selection.size() != 1) //only after we checked the 'one project' case return false; /* * special case: if both source references and resources are in clipboard - disable this action * if a compilation unit is selected. * this is important in the case when a type is copied to the clipboard - we put also its compilation unit */ TypedSource[] typedSource= getClipboardSourceReference(); if (selection.getFirstElement() instanceof ICompilationUnit && typedSource != null && typedSource.length != 0) return false; if (StructuredSelectionUtil.getResources(selection).length != 1) return false; if (resourceData == null) return ClipboardActionUtil.getFirstResource(selection) instanceof IContainer; return canActivateCopyRefactoring(resourceData, ClipboardActionUtil.getFirstResource(selection)); } private boolean canPasteFiles(IStructuredSelection selection) { return (getClipboardFiles() != null) && canPasteFilesOn(selection.getFirstElement()); } private static boolean canPasteFilesOn(Object target) { boolean isPackageFragment= target instanceof IPackageFragment; boolean isJavaProject= target instanceof IJavaProject; boolean isPackageFragmentRoot= target instanceof IPackageFragmentRoot; boolean isContainer= target instanceof IContainer; if (!(isPackageFragment || isJavaProject || isPackageFragmentRoot || isContainer)) return false; if (isContainer) { IContainer container= (IContainer)target; if (!container.isReadOnly()) return true; } else { IJavaElement element= (IJavaElement)target; if (!element.isReadOnly()) return true; } return false; } private static boolean canActivateCopyRefactoring(IResource[] resourceData, IResource selectedResource) { try{ CopyRefactoring ref= createCopyRefactoring(resourceData); if (! ref.checkActivation(new NullProgressMonitor()).isOK()) return false; return ref.isValidDestination(ClipboardActionUtil.tryConvertingToJava(selectedResource)); } catch (JavaModelException e){ return false; } } //-- helpers private IResource getFirstSelectedResource(IStructuredSelection selection){ return ClipboardActionUtil.getFirstResource(selection); } private String[] getClipboardFiles() { return ((String[])fClipboard.getContents(FileTransfer.getInstance())); } private IResource[] getClipboardResources() { return ((IResource[])fClipboard.getContents(ResourceTransfer.getInstance())); } private TypedSource[] getClipboardSourceReference() { return ((TypedSource[])fClipboard.getContents(TypedSourceTransfer.getInstance())); } private static CopyRefactoring createCopyRefactoring(IResource[] resourceData) { return new CopyRefactoring(ClipboardActionUtil.getConvertedResources(resourceData), new CopyQueries()); } }
25,729
Bug 25729 Java editor opening up build.xml
Using Java editor to open .xml usually works. But when opening Ant build file (build.xml), it gives the NullPointerException and the IDE no longer works. !ENTRY org.eclipse.ui 4 4 Nov 05, 2002 09:28:39.131 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Nov 05, 2002 09:28:39.131 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at org.eclipse.ui.internal.WorkbenchWindow$12.shellActivated(WorkbenchWindow. java:1454) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:157) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:850) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:830) at org.eclipse.swt.widgets.Decorations.WM_ACTIVATE (Decorations.java:1246) at org.eclipse.swt.widgets.Shell.WM_ACTIVATE(Shell.java:1139) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2689) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1218) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2172) at org.eclipse.swt.internal.win32.OS.DestroyWindow(Native Method) at org.eclipse.swt.widgets.Control.destroyWidget(Control.java:497) at org.eclipse.swt.widgets.Widget.dispose(Widget.java:358) at org.eclipse.swt.widgets.Shell.dispose(Shell.java:470) at org.eclipse.jface.window.Window.close(Window.java:223) at org.eclipse.jface.dialogs.Dialog.close(Dialog.java:676) at org.eclipse.jface.dialogs.MessageDialog.buttonPressed(MessageDialog.java:1 41) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.jface.dialogs.MessageDialog.openQuestion(MessageDialog.java:31 8) at org.eclipse.ui.internal.Workbench$1.handleException(Workbench.java:222) at org.eclipse.core.internal.runtime.InternalPlatform.handleException(Interna lPlatform.java:439) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.ja va:841) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.Workbench.busyClose(Workbench.java:208) at org.eclipse.ui.internal.Workbench.access$5(Workbench.java:206) at org.eclipse.ui.internal.Workbench$4.run(Workbench.java:363) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.Workbench.close(Workbench.java:361) at org.eclipse.ui.internal.Workbench.close(Workbench.java:353) at org.eclipse.ui.internal.Workbench.close(Workbench.java:347) at org.eclipse.ui.internal.WorkbenchWindow.busyClose(WorkbenchWindow.java:355 ) at org.eclipse.ui.internal.WorkbenchWindow.access$3(WorkbenchWindow.java:348) at org.eclipse.ui.internal.WorkbenchWindow$2.run(WorkbenchWindow.java:404) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.ui.internal.WorkbenchWindow.close(WorkbenchWindow.java:402) at org.eclipse.jface.window.Window.handleShellCloseEvent (Window.java:482) at org.eclipse.jface.window.Window$2.shellClosed(Window.java:433) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:152) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:850) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:834) at org.eclipse.swt.widgets.Decorations.WM_CLOSE(Decorations.java:1258) at org.eclipse.swt.widgets.Shell.WM_CLOSE(Shell.java:1148) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2692) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1218) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2172) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java:1281) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java:73) at org.eclipse.swt.widgets.Shell.callWindowProc(Shell.java:392) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2766) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1218) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2172) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1286) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1408) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1419) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1402) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.j ava:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java: 39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorIm pl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
verified fixed
d4a10a7
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-13T16:21:13Z
2002-11-05T15:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.AnnotationRulerColumn; import org.eclipse.jface.text.source.CompositeRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.IVerticalRulerColumn; import org.eclipse.jface.text.source.LineNumberRulerColumn; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPartService; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.editors.text.DefaultEncodingSupport; import org.eclipse.ui.editors.text.IEncodingSupport; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.texteditor.AddTaskAction; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.StatusTextEditor; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.ui.text.IColorManager; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; /** * Java specific text editor. */ public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider { /** * "Smart" runnable for updating the outline page's selection. */ class OutlinePageSelectionUpdater implements Runnable { /** Has the runnable already been posted? */ private boolean fPosted= false; public OutlinePageSelectionUpdater() { } /* * @see Runnable#run() */ public void run() { synchronizeOutlinePageSelection(); fPosted= false; } /** * Posts this runnable into the event queue. */ public void post() { if (fPosted) return; Shell shell= getSite().getShell(); if (shell != null & !shell.isDisposed()) { fPosted= true; shell.getDisplay().asyncExec(this); } } }; class SelectionChangedListener implements ISelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; /** * Link mode. */ class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, MouseTrackListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener { /** The session is active. */ private boolean fActive; /** The currently active style range. */ private IRegion fActiveRegion; /** The hand cursor. */ private Cursor fCursor; /** The default cursor. */ private Cursor fDefaultCursor; /** The link color. */ private Color fColor; public void deactivate() { if (!fActive) return; repairRepresentation(); fActive= false; } public void install() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; updateColor(sourceViewer); sourceViewer.addTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.addDocumentListener(this); text.addKeyListener(this); text.addMouseListener(this); text.addMouseMoveListener(this); text.addFocusListener(this); text.addPaintListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.addPropertyChangeListener(this); } public void uninstall() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; sourceViewer.removeTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.removeDocumentListener(this); text.removeKeyListener(this); text.removeMouseListener(this); text.removeMouseMoveListener(this); text.removeFocusListener(this); text.removePaintListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.removePropertyChangeListener(this); if (fColor != null) { fColor.dispose(); fColor= null; } if (fCursor != null) { fCursor.dispose(); fCursor= null; } } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(JavaEditor.LINK_COLOR)) { ISourceViewer viewer= getSourceViewer(); if (viewer != null) updateColor(viewer); } } private void updateColor(ISourceViewer viewer) { if (fColor != null) fColor.dispose(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display); } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } private void repairRepresentation() { if (fActiveRegion == null) return; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { resetCursor(viewer); int offset= fActiveRegion.getOffset(); int length= fActiveRegion.getLength(); // remove style if (viewer instanceof ITextViewerExtension2) ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length); else viewer.invalidateTextPresentation(); // remove underline offset -= viewer.getVisibleRegion().getOffset(); StyledText text= viewer.getTextWidget(); text.redrawRange(offset, length, true); } fActiveRegion= null; } private IJavaElement getInput(JavaEditor editor) { if (editor == null) return null; IEditorInput input= editor.getEditorInput(); if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(input); } // will eventually be replaced by a method provided by jdt.core private IRegion selectWord(IDocument document, int anchor) { try { int offset= anchor; char c; while (offset >= 0) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; --offset; } int start= offset; offset= anchor; int length= document.getLength(); while (offset < length) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; ++offset; } int end= offset; if (start == end) return new Region(start, 0); else return new Region(start + 1, end - start - 1); } catch (BadLocationException x) { return null; } } IRegion getCurrentTextRegion(ISourceViewer viewer) { int offset= getCurrentTextOffset(viewer); if (offset == -1) return null; IJavaElement input= SelectionConverter.getInput(JavaEditor.this); if (input == null) return null; try { IJavaElement[] elements= ((ICodeAssist) input).codeSelect(offset, 0); if (elements == null || elements.length == 0) return null; return selectWord(viewer.getDocument(), offset); } catch (JavaModelException e) { return null; } } private int getCurrentTextOffset(ISourceViewer viewer) { try { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return -1; Display display= text.getDisplay(); Point absolutePosition= display.getCursorLocation(); Point relativePosition= text.toControl(absolutePosition); return text.getOffsetAtLocation(relativePosition) + viewer.getVisibleRegion().getOffset(); } catch (IllegalArgumentException e) { return -1; } } private void highlightRegion(ISourceViewer viewer, IRegion region) { if (region.equals(fActiveRegion)) return; repairRepresentation(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; // highlight region int offset= region.getOffset() - viewer.getVisibleRegion().getOffset(); int length= region.getLength(); StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset); Color foregroundColor= fColor; Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor); text.setStyleRange(styleRange); // underline text.redrawRange(offset, length, true); fActiveRegion= region; } private void activateCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); if (fCursor == null) fCursor= new Cursor(display, SWT.CURSOR_HAND); text.setCursor(fCursor); } private void resetCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); if (fDefaultCursor == null) fDefaultCursor= new Cursor(display, SWT.CURSOR_IBEAM); text.setCursor(fDefaultCursor); if (fCursor != null) { fCursor.dispose(); fCursor= null; } } /* * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) */ public void keyPressed(KeyEvent event) { if (fActive) { deactivate(); return; } if (event.keyCode != SWT.CTRL) { deactivate(); return; } fActive= true; ISourceViewer viewer= getSourceViewer(); if (viewer == null) return; IRegion region= getCurrentTextRegion(viewer); if (region == null) return; // removed for #25871 // highlightRegion(viewer, region); // activateCursor(viewer); } /* * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) */ public void keyReleased(KeyEvent event) { if (!fActive) return; deactivate(); } /* * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) */ public void mouseDoubleClick(MouseEvent e) {} /* * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) */ public void mouseDown(MouseEvent event) { if (!fActive) return; if (event.stateMask != SWT.CTRL) { deactivate(); return; } if (event.button != 1) { deactivate(); return; } } /* * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) */ public void mouseUp(MouseEvent e) { if (!fActive) return; if (e.button != 1) { deactivate(); return; } deactivate(); IAction action= getAction("OpenEditor"); //$NON-NLS-1$ if (action == null) return; action.run(); } /* * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) */ public void mouseMove(MouseEvent event) { if (!fActive) { if (event.stateMask != SWT.CTRL) return; // Ctrl was already pressed fActive= true; } ISourceViewer viewer= getSourceViewer(); if (viewer == null) { deactivate(); return; } StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) { deactivate(); return; } if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) { deactivate(); return; } IRegion region= getCurrentTextRegion(viewer); if (region == null) { repairRepresentation(); return; } highlightRegion(viewer, region); activateCursor(viewer); } /* * @see org.eclipse.swt.events.MouseTrackListener#mouseEnter(org.eclipse.swt.events.MouseEvent) */ public void mouseEnter(MouseEvent e) {} /* * @see org.eclipse.swt.events.MouseTrackListener#mouseExit(org.eclipse.swt.events.MouseEvent) */ public void mouseExit(MouseEvent e) { repairRepresentation(); } /* * @see org.eclipse.swt.events.MouseTrackListener#mouseHover(org.eclipse.swt.events.MouseEvent) */ public void mouseHover(MouseEvent e) {} /* * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) */ public void focusGained(FocusEvent e) {} /* * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent event) { deactivate(); } /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { deactivate(); } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput == null) return; deactivate(); oldInput.removeDocumentListener(this); } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput == null) return; newInput.addDocumentListener(this); } /* * @see PaintListener#paintControl(PaintEvent) */ public void paintControl(PaintEvent event) { if (fActiveRegion == null) return; ISourceViewer viewer= getSourceViewer(); if (viewer == null) return; IRegion region= viewer.getVisibleRegion(); if (!includes(region, fActiveRegion)) return; StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; int offset= fActiveRegion.getOffset() - region.getOffset(); int length= fActiveRegion.getLength(); // support for bidi Point minLocation= getMinimumLocation(text, offset, length); Point maxLocation= getMaximumLocation(text, offset, length); int x1= minLocation.x; int x2= minLocation.x + maxLocation.x - minLocation.x - 1; int y= minLocation.y + text.getLineHeight() - 1; GC gc= event.gc; gc.setForeground(fColor); gc.drawLine(x1, y, x2, y); } private boolean includes(IRegion region, IRegion position) { return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); } private Point getMinimumLocation(StyledText text, int offset, int length) { Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x < minLocation.x) minLocation.x= location.x; if (location.y < minLocation.y) minLocation.y= location.y; } return minLocation; } private Point getMaximumLocation(StyledText text, int offset, int length) { Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x > maxLocation.x) maxLocation.x= location.x; if (location.y > maxLocation.y) maxLocation.y= location.y; } return maxLocation; } } /** * This action dispatches into two behaviours: If there is no current text * hover, the javadoc is displayed using information presenter. If there is * a current text hover, it is converted into a information presenter in * order to make it sticky. */ class InformationDispatchAction extends TextEditorAction { /** The wrapped text operation action. */ private final TextOperationAction fTextOperationAction; /** * Creates a dispatch action. */ public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) { super(resourceBundle, prefix, JavaEditor.this); if (textOperationAction == null) throw new IllegalArgumentException(); fTextOperationAction= textOperationAction; } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) { fTextOperationAction.run(); return; } if (! (sourceViewer instanceof ITextViewerExtension2)) { fTextOperationAction.run(); return; } ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer; // does a text hover exist? ITextHover textHover= textViewerExtension2.getCurrentTextHover(); if (textHover == null) { fTextOperationAction.run(); return; } Point hoverEventLocation= textViewerExtension2.getHoverEventLocation(); int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y); if (offset == -1) { fTextOperationAction.run(); return; } try { // get the text hover content IDocument document= sourceViewer.getDocument(); String contentType= document.getContentType(offset); final IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset); if (hoverRegion == null) return; final String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion); // with information provider IInformationProvider informationProvider= new IInformationProvider() { /* * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int) */ public IRegion getSubject(ITextViewer textViewer, int offset) { return hoverRegion; } /* * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) */ public String getInformation(ITextViewer textViewer, IRegion subject) { return hoverInfo; } }; fInformationPresenter.setOffset(offset); fInformationPresenter.setInformationProvider(informationProvider, contentType); fInformationPresenter.showInformation(); } catch (BadLocationException e) { } } // modified version from TextViewer private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { StyledText styledText= textViewer.getTextWidget(); IDocument document= textViewer.getDocument(); IRegion visibleRegion= textViewer.getVisibleRegion(); if (document == null) return -1; try { return styledText.getOffsetAtLocation(new Point(x, y)) + visibleRegion.getOffset(); } catch (IllegalArgumentException e) { return -1; } } } /** Preference key for showing the line number ruler */ public final static String LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$ /** Preference key for the foreground color of the line numbers */ public final static String LINE_NUMBER_COLOR= "lineNumberColor"; //$NON-NLS-1$ /** Preference key for the link color */ public final static String LINK_COLOR= "linkColor"; //$NON-NLS-1$ /** Preference key for the default hover */ public static final String DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$ /** Preference key for hover while no modifier is pressed */ public static final String NONE_HOVER= "noneHover"; //$NON-NLS-1$ /** Preference key for hover while Ctrl modifier is pressed */ public static final String CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$ /** Preference key for hover while Shift modifier is pressed */ public static final String SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$ /** Preference key for hover while Ctrl+Alt modifiers are pressed */ public static final String CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$ /** Preference key for hover while Ctrl+Alt+Shift modifiers are pressed */ public static final String CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$ /** Preference key for hover while Ctrl+Shift modifiers are pressed */ public static final String CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$ /** Preference key for hover while Alt+Shift modifiers are pressed */ public static final String ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$ /** Id indicating no hover is configured */ public static final String NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$ /** Hover id indicating the default hover */ public static final String DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$ /** The outline page */ protected JavaOutlinePage fOutlinePage; /** Outliner context menu Id */ protected String fOutlinerContextMenuId; /** The selection changed listener */ protected ISelectionChangedListener fSelectionChangedListener= new SelectionChangedListener(); /** The outline page selection updater */ private OutlinePageSelectionUpdater fUpdater; /** Indicates whether this editor should react on outline page selection changes */ private int fIgnoreOutlinePageSelection; /** The line number ruler column */ private LineNumberRulerColumn fLineNumberRulerColumn; /** This editor's encoding support */ private DefaultEncodingSupport fEncodingSupport; /** The mouse listener */ private MouseClickListener fMouseListener; /** The information presenter. */ private InformationPresenter fInformationPresenter; protected CompositeActionGroup fActionGroups; private CompositeActionGroup fContextMenuGroup; /** * Returns the most narrow java element including the given offset * * @param offset the offset inside of the requested element */ abstract protected IJavaElement getElementAt(int offset); /** * Returns the java element of this editor's input corresponding to the given IJavaElement */ abstract protected IJavaElement getCorrespondingElement(IJavaElement element); /** * Sets the input of the editor's outline page. */ abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input); /** * Default constructor. */ public JavaEditor() { super(); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this)); setRangeIndicator(new DefaultRangeIndicator()); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); if (JavaEditorPreferencePage.synchronizeOutlineOnCursorMove()) fUpdater= new OutlinePageSelectionUpdater(); } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { ISourceViewer viewer= createJavaSourceViewer(parent, ruler, styles); StyledText text= viewer.getTextWidget(); text.addBidiSegmentListener(new BidiSegmentListener() { public void lineGetSegments(BidiSegmentEvent event) { event.segments= getBidiLineSegments(event.lineOffset, event.lineText); } }); JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); return viewer; } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return super.createSourceViewer(parent, ruler, styles); } /* * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.affectsBehavior(event); } /** * Sets the outliner's context menu ID. */ protected void setOutlinerContextMenuId(String menuId) { fOutlinerContextMenuId= menuId; } /** * Returns the standard action group of this editor. */ protected ActionGroup getActionGroup() { return fActionGroups; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN)); menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW)); ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /** * Creates the outline page used with this editor. */ protected JavaOutlinePage createOutlinePage() { JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this); page.addSelectionChangedListener(fSelectionChangedListener); setOutlinePageInput(page, getEditorInput()); return page; } /** * Informs the editor that its outliner has been closed. */ public void outlinePageClosed() { if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage= null; resetHighlightRange(); } } /** * Synchronizes the outliner selection with the actual cursor * position in the editor. */ public void synchronizeOutlinePageSelection() { if (isEditingScriptRunning()) return; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null || fOutlinePage == null) return; StyledText styledText= sourceViewer.getTextWidget(); if (styledText == null) return; int offset= sourceViewer.getVisibleRegion().getOffset(); int caret= offset + styledText.getCaretOffset(); IJavaElement element= getElementAt(caret); if (element instanceof ISourceReference) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select((ISourceReference) element); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } } /* * Get the desktop's StatusLineManager */ protected IStatusLineManager getStatusLineManager() { IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) { return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); } return null; } /* * @see AbstractTextEditor#getAdapter(Class) */ public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { if (fOutlinePage == null) fOutlinePage= createOutlinePage(); return fOutlinePage; } if (IEncodingSupport.class.equals(required)) return fEncodingSupport; return super.getAdapter(required); } protected void setSelection(ISourceReference reference, boolean moveCursor) { ISelection selection= getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection= (TextSelection) selection; if (textSelection.getOffset() != 0 || textSelection.getLength() != 0) markInNavigationHistory(); } if (reference != null) { StyledText textWidget= null; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer != null) textWidget= sourceViewer.getTextWidget(); if (textWidget == null) return; try { ISourceRange range= reference.getSourceRange(); if (range == null) return; int offset= range.getOffset(); int length= range.getLength(); if (offset < 0 || length < 0) return; textWidget.setRedraw(false); setHighlightRange(offset, length, moveCursor); if (!moveCursor) return; offset= -1; length= -1; if (reference instanceof IMember) { range= ((IMember) reference).getNameRange(); if (range != null) { offset= range.getOffset(); length= range.getLength(); } } else if (reference instanceof IImportDeclaration) { String name= ((IImportDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); offset= range.getOffset() + content.indexOf(name); length= name.length(); } } else if (reference instanceof IPackageDeclaration) { String name= ((IPackageDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); offset= range.getOffset() + content.indexOf(name); length= name.length(); } } if (offset > -1 && length > 0) { sourceViewer.revealRange(offset, length); sourceViewer.setSelectedRange(offset, length); } } catch (JavaModelException x) { } catch (IllegalArgumentException x) { } finally { if (textWidget != null) textWidget.setRedraw(true); } } else if (moveCursor) { resetHighlightRange(); } markInNavigationHistory(); } public void setSelection(IJavaElement element) { if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) { /* * If the element is an ICompilationUnit this unit is either the input * of this editor or not being displayed. In both cases, nothing should * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) */ return; } IJavaElement corresponding= getCorrespondingElement(element); if (corresponding instanceof ISourceReference) { ISourceReference reference= (ISourceReference) corresponding; // set hightlight range setSelection(reference, true); // set outliner selection if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select(reference); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } } } public synchronized void editingScriptStarted() { ++ fIgnoreOutlinePageSelection; } public synchronized void editingScriptEnded() { -- fIgnoreOutlinePageSelection; } public synchronized boolean isEditingScriptRunning() { return (fIgnoreOutlinePageSelection > 0); } protected void doSelectionChanged(SelectionChangedEvent event) { ISourceReference reference= null; ISelection selection= event.getSelection(); Iterator iter= ((IStructuredSelection) selection).iterator(); while (iter.hasNext()) { Object o= iter.next(); if (o instanceof ISourceReference) { reference= (ISourceReference) o; break; } } if (!isActivePart() && JavaPlugin.getActivePage() != null) JavaPlugin.getActivePage().bringToTop(this); try { editingScriptStarted(); setSelection(reference, !isActivePart()); } finally { editingScriptEnded(); } } /* * @see AbstractTextEditor#adjustHighlightRange(int, int) */ protected void adjustHighlightRange(int offset, int length) { try { IJavaElement element= getElementAt(offset); while (element instanceof ISourceReference) { ISourceRange range= ((ISourceReference) element).getSourceRange(); if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) { setHighlightRange(range.getOffset(), range.getLength(), true); if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select((ISourceReference) element); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } return; } element= element.getParent(); } } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); } resetHighlightRange(); } protected boolean isActivePart() { IWorkbenchWindow window= getSite().getWorkbenchWindow(); IPartService service= window.getPartService(); IWorkbenchPart part= service.getActivePart(); return part != null && part.equals(this); } /* * @see StatusTextEditor#getStatusHeader(IStatus) */ protected String getStatusHeader(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusHeader(status); if (message != null) return message; } return super.getStatusHeader(status); } /* * @see StatusTextEditor#getStatusBanner(IStatus) */ protected String getStatusBanner(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusBanner(status); if (message != null) return message; } return super.getStatusBanner(status); } /* * @see StatusTextEditor#getStatusMessage(IStatus) */ protected String getStatusMessage(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusMessage(status); if (message != null) return message; } return super.getStatusMessage(status); } /* * @see AbstractTextEditor#doSetInput */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (fEncodingSupport != null) fEncodingSupport.reset(); setOutlinePageInput(fOutlinePage, input); } /* * @see IWorkbenchPart#dispose() */ public void dispose() { if (fMouseListener != null) { fMouseListener.uninstall(); fMouseListener= null; } if (fEncodingSupport != null) { fEncodingSupport.dispose(); fEncodingSupport= null; } super.dispose(); } protected void createActions() { super.createActions(); ResourceAction action= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK); setAction(ITextEditorActionConstants.ADD_TASK, action); ActionGroup oeg, ovg, sg, jsg; fActionGroups= new CompositeActionGroup(new ActionGroup[] { oeg= new OpenEditorActionGroup(this), ovg= new OpenViewActionGroup(this), sg= new ShowActionGroup(this), jsg= new JavaSearchActionGroup(this) }); fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg}); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ action= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) action); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC); setAction("ShowJavaDoc", action); //$NON-NLS-1$ fEncodingSupport= new DefaultEncodingSupport(); fEncodingSupport.initialize(this); if (fMouseListener == null) { fMouseListener= new MouseClickListener(); fMouseListener.install(); } } 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); } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; String property= event.getProperty(); if (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) { Object value= event.getNewValue(); if (value instanceof Integer) { sourceViewer.getTextWidget().setTabs(((Integer) value).intValue()); } else if (value instanceof String) { sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value)); } return; } if (LINE_NUMBER_RULER.equals(property)) { if (isLineNumberRulerVisible()) showLineNumberRuler(); else hideLineNumberRuler(); return; } if (fLineNumberRulerColumn != null && (LINE_NUMBER_COLOR.equals(property) || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || PREFERENCE_COLOR_BACKGROUND.equals(property))) { initializeLineNumberRulerColumn(fLineNumberRulerColumn); } if (PreferenceConstants.EDITOR_SHOW_HOVER.equals(property)) { updateHoverBehavior(); } if (isJavaEditorHoverProperty(property)) { updateHoverBehavior(); } } finally { super.handlePreferenceStoreChanged(event); } } private boolean isJavaEditorHoverProperty(String property) { return JavaEditor.DEFAULT_HOVER.equals(property) || JavaEditor.NONE_HOVER.equals(property) || JavaEditor.CTRL_HOVER.equals(property) || JavaEditor.SHIFT_HOVER.equals(property) || JavaEditor.CTRL_ALT_HOVER.equals(property) || JavaEditor.CTRL_SHIFT_HOVER.equals(property) || JavaEditor.CTRL_ALT_SHIFT_HOVER.equals(property) || JavaEditor.ALT_SHIFT_HOVER.equals(property); } /** * Shows the line number ruler column. */ private void showLineNumberRuler() { IVerticalRuler v= getVerticalRuler(); if (v instanceof CompositeRuler) { CompositeRuler c= (CompositeRuler) v; c.addDecorator(1, createLineNumberRulerColumn()); } } /** * Hides the line number ruler column. */ private void hideLineNumberRuler() { IVerticalRuler v= getVerticalRuler(); if (v instanceof CompositeRuler) { CompositeRuler c= (CompositeRuler) v; c.removeDecorator(1); } } /** * Return whether the line number ruler column should be * visible according to the preference store settings. * @return <code>true</code> if the line numbers should be visible */ private boolean isLineNumberRulerVisible() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(LINE_NUMBER_RULER); } /** * Returns a segmentation of the line of the given document appropriate for bidi rendering. * The default implementation returns only the string literals of a java code line as segments. * * @param document the document * @param lineOffset the offset of the line * @return the line's bidi segmentation * @throws BadLocationException in case lineOffset is not valid in document */ public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException { IRegion line= document.getLineInformationOfOffset(lineOffset); ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength()); List segmentation= new ArrayList(); for (int i= 0; i < linePartitioning.length; i++) { if (JavaPartitionScanner.JAVA_STRING.equals(linePartitioning[i].getType())) segmentation.add(linePartitioning[i]); } if (segmentation.size() == 0) return null; int size= segmentation.size(); int[] segments= new int[size * 2 + 1]; int j= 0; for (int i= 0; i < size; i++) { ITypedRegion segment= (ITypedRegion) segmentation.get(i); if (i == 0) segments[j++]= 0; int offset= segment.getOffset() - lineOffset; if (offset > segments[j - 1]) segments[j++]= offset; if (offset + segment.getLength() >= line.getLength()) break; segments[j++]= offset + segment.getLength(); } if (j < segments.length) { int[] result= new int[j]; System.arraycopy(segments, 0, result, 0, j); segments= result; } return segments; } /** * Returns a segmentation of the given line appropriate for bidi rendering. The default * implementation returns only the string literals of a java code line as segments. * * @param lineOffset the offset of the line * @param line the content of the line * @return the line's bidi segmentation */ protected int[] getBidiLineSegments(int lineOffset, String line) { IDocumentProvider provider= getDocumentProvider(); if (provider != null) { IDocument document= provider.getDocument(getEditorInput()); if (document != null) try { return getBidiLineSegments(document, lineOffset); } catch (BadLocationException x) { // ignore } } return null; } /* * @see AbstractTextEditor#handleCursorPositionChanged() */ protected void handleCursorPositionChanged() { super.handleCursorPositionChanged(); if (!isEditingScriptRunning() && fUpdater != null) fUpdater.post(); } /** * Initializes the given line number ruler column from the preference store. * @param rulerColumn the ruler column to be initialized */ protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); IColorManager manager= textTools.getColorManager(); IPreferenceStore store= getPreferenceStore(); if (store != null) { RGB rgb= null; // foreground color if (store.contains(LINE_NUMBER_COLOR)) { if (store.isDefault(LINE_NUMBER_COLOR)) rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR); else rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR); } rulerColumn.setForeground(manager.getColor(rgb)); rgb= null; // background color if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { if (store.contains(PREFERENCE_COLOR_BACKGROUND)) { if (store.isDefault(PREFERENCE_COLOR_BACKGROUND)) rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND); else rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND); } } rulerColumn.setBackground(manager.getColor(rgb)); } } /** * Creates a new line number ruler column that is appropriately initialized. */ protected IVerticalRulerColumn createLineNumberRulerColumn() { fLineNumberRulerColumn= new LineNumberRulerColumn(); initializeLineNumberRulerColumn(fLineNumberRulerColumn); return fLineNumberRulerColumn; } /* * @see AbstractTextEditor#createVerticalRuler() */ protected IVerticalRuler createVerticalRuler() { CompositeRuler ruler= new CompositeRuler(); ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH)); if (isLineNumberRulerVisible()) ruler.addDecorator(1, createLineNumberRulerColumn()); return ruler; } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() */ protected void updatePropertyDependentActions() { super.updatePropertyDependentActions(); if (fEncodingSupport != null) fEncodingSupport.reset(); } /* * Update the hovering behavior depending on the preferences. */ private void updateHoverBehavior() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(getSourceViewer()); for (int i= 0; i < types.length; i++) { String t= types[i]; int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension2) { if (stateMasks != null) { for (int j= 0; j < stateMasks.length; j++) { int stateMask= stateMasks[j]; ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover= configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } /* * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return getEditorInput().getAdapter(IJavaElement.class); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) */ protected void doSetSelection(ISelection selection) { super.doSetSelection(selection); synchronizeOutlinePageSelection(); } /* * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. * widgets.Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); ISourceViewer sourceViewer= getSourceViewer(); SourceViewerConfiguration sourceViewerConfiguration= getSourceViewerConfiguration(); IInformationControlCreator informationControlCreator= new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { boolean cutDown= false; int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown)); } }; fInformationPresenter= new InformationPresenter(informationControlCreator); fInformationPresenter.setSizeConstraints(60, 10, true, true); fInformationPresenter.install(sourceViewer); } }
26,287
Bug 26287 NPE in Javadoc wizard
!ENTRY org.eclipse.ui 4 4 Nov 14, 2002 14:19:00.445 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Nov 14, 2002 14:19:00.485 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javadocexport.JavadocStandardWizardPage.findReferen cedElements(JavadocStandardWizardPage.java:324) at org.eclipse.jdt.internal.ui.javadocexport.JavadocStandardWizardPage.findRE (JavadocStandardWizardPage.java:291) at org.eclipse.jdt.internal.ui.javadocexport.JavadocStandardWizardPage.updateCheck edListGroup(JavadocStandardWizardPage.java:453) at org.eclipse.jdt.internal.ui.javadocexport.JavadocStandardWizardPage.createListD ialogField(JavadocStandardWizardPage.java:239) at org.eclipse.jdt.internal.ui.javadocexport.JavadocStandardWizardPage.createContr ol(JavadocStandardWizardPage.java:112) at org.eclipse.jface.wizard.Wizard.createPageControls(Wizard.java:165) at org.eclipse.jface.wizard.WizardDialog.createPageControls (WizardDialog.java:498) at org.eclipse.jface.wizard.WizardDialog.setWizard (WizardDialog.java:839) at org.eclipse.jface.wizard.WizardDialog.showPage (WizardDialog.java:873) at org.eclipse.jface.wizard.WizardDialog.nextPressed (WizardDialog.java:646) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:304) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:397) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.actions.ExportResourcesAction.run (ExportResourcesAction.java:84) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1435) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1418) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24)
resolved fixed
0f49685
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-14T16:59:21Z
2002-11-14T13:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocStandardWizardPage.java
package org.eclipse.jdt.internal.ui.javadocexport; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.help.WorkbenchHelp; 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.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.preferences.JavadocConfigurationBlock; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; 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.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; public class JavadocStandardWizardPage extends JavadocWizardPage { private JavadocOptionsManager fStore; private JavadocWizard fWizard; private Composite fUpperComposite; private Group fBasicOptionsGroup; private Group fTagsGroup; private Button fTitleButton; private Text fTitleText; protected Text fStyleSheetText; protected FlaggedButton fDeprecatedList; protected FlaggedButton fAuthorCheck; protected FlaggedButton fVersionCheck; protected FlaggedButton fDeprecatedCheck; protected FlaggedButton fHierarchyCheck; protected FlaggedButton fNavigatorCheck; protected FlaggedButton fIndexCheck; protected FlaggedButton fSeperatedIndexCheck; protected FlaggedButton fUse; protected Button fStyleSheetBrowseButton; protected Button fStyleSheetButton; private CheckedListDialogField fListDialogField; private final int STYLESHEETSTATUS= 0; private StatusInfo fStyleSheetStatus; protected ArrayList fButtonsList; private Map fTempLinks; public JavadocStandardWizardPage(String pageName, JavadocOptionsManager store) { super(pageName); setDescription(JavadocExportMessages.getString("JavadcoStandardWizardPage.description")); //$NON-NLS-1$ fStore= store; fButtonsList= new ArrayList(); fStyleSheetStatus= new StatusInfo(); } /* * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); fWizard= (JavadocWizard) this.getWizard(); fUpperComposite= new Composite(parent, SWT.NONE); fUpperComposite.setLayoutData(createGridData(GridData.FILL_VERTICAL | GridData.FILL_HORIZONTAL, 1, 0)); GridLayout layout= createGridLayout(4); layout.marginHeight= 0; fUpperComposite.setLayout(layout); createBasicOptionsGroup(fUpperComposite); createTagOptionsGroup(fUpperComposite); createListDialogField(fUpperComposite); createStyleSheetGroup(fUpperComposite); setControl(fUpperComposite); WorkbenchHelp.setHelp(fUpperComposite, IJavaHelpContextIds.JAVADOC_STANDARD_PAGE); } private void createBasicOptionsGroup(Composite composite) { fTitleButton= createButton(composite, SWT.CHECK, JavadocExportMessages.getString("JavadcoStandardWizardPage.titlebutton.label"), createGridData(1)); //$NON-NLS-1$ fTitleText= createText(composite, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 3, 0)); String text= fStore.getTitle(); if (!text.equals("")) { //$NON-NLS-1$ fTitleText.setText(text); fTitleButton.setSelection(true); } else fTitleText.setEnabled(false); fBasicOptionsGroup= new Group(composite, SWT.SHADOW_ETCHED_IN); fBasicOptionsGroup.setLayout(createGridLayout(1)); fBasicOptionsGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL, 2, 0)); fBasicOptionsGroup.setText(JavadocExportMessages.getString("JavadcoStandardWizardPage.basicgroup.label")); //$NON-NLS-1$ fUse= new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.usebutton.label"), new GridData(GridData.FILL_HORIZONTAL), fStore.USE, true); //$NON-NLS-1$ fHierarchyCheck= new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.hierarchybutton.label"), new GridData(GridData.FILL_HORIZONTAL), fStore.NOTREE, false); //$NON-NLS-1$ fNavigatorCheck= new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.navigartorbutton.label"), new GridData(GridData.FILL_HORIZONTAL), fStore.NONAVBAR, false); //$NON-NLS-1$ fIndexCheck= new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.indexbutton.label"), new GridData(GridData.FILL_HORIZONTAL), fStore.NOINDEX, false); //$NON-NLS-1$ fSeperatedIndexCheck= new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.seperateindexbutton.label"), createGridData(GridData.GRAB_HORIZONTAL, 1, convertWidthInCharsToPixels(3)), fStore.SPLITINDEX, true); //$NON-NLS-1$ fSeperatedIndexCheck.getButton().setEnabled(fIndexCheck.getButton().getSelection()); fIndexCheck.getButton().addSelectionListener(new ToggleSelectionAdapter(new Control[] { fSeperatedIndexCheck.getButton()}) { public void validate() { } }); fTitleButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fTitleText }) { public void validate() { } }); } private void createTagOptionsGroup(Composite composite) { fTagsGroup= new Group(composite, SWT.SHADOW_ETCHED_IN); fTagsGroup.setLayout(createGridLayout(1)); fTagsGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL, 2, 0)); fTagsGroup.setText(JavadocExportMessages.getString("JavadcoStandardWizardPage.tagsgroup.label")); //$NON-NLS-1$ fAuthorCheck= new FlaggedButton(fTagsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.authorbutton.label"), new GridData(GridData.FILL_HORIZONTAL), fStore.AUTHOR, true); //$NON-NLS-1$ fVersionCheck= new FlaggedButton(fTagsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.versionbutton.label"), new GridData(GridData.FILL_HORIZONTAL), fStore.VERSION, true); //$NON-NLS-1$ fDeprecatedCheck= new FlaggedButton(fTagsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.deprecatedbutton.label"), new GridData(GridData.FILL_HORIZONTAL), fStore.NODEPRECATED, false); //$NON-NLS-1$ fDeprecatedList= new FlaggedButton(fTagsGroup, JavadocExportMessages.getString("JavadcoStandardWizardPage.deprecatedlistbutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, convertWidthInCharsToPixels(3)), fStore.NODEPRECATEDLIST, false); //$NON-NLS-1$ fDeprecatedList.getButton().setEnabled(fDeprecatedCheck.getButton().getSelection()); fDeprecatedCheck.getButton().addSelectionListener(new ToggleSelectionAdapter(new Control[] { fDeprecatedList.getButton()}) { public void validate() { } }); } //end createTagOptionsGroup private void createStyleSheetGroup(Composite composite) { Composite c= new Composite(composite, SWT.NONE); c.setLayout(createGridLayout(3)); c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 4, 0)); ((GridLayout) c.getLayout()).marginWidth= 0; fStyleSheetButton= createButton(c, SWT.CHECK, JavadocExportMessages.getString("JavadcoStandardWizardPage.stylesheettext.label"), createGridData(1)); //$NON-NLS-1$ fStyleSheetText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //there really aught to be a way to specify this ((GridData) fStyleSheetText.getLayoutData()).widthHint= 200; fStyleSheetBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.getString("JavadocStandardWizardPage.stylesheetbrowsebutton.label"), createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0)); //$NON-NLS-1$ SWTUtil.setButtonDimensionHint(fStyleSheetBrowseButton); String str= fStore.getStyleSheet(); if (str.equals("")) { //$NON-NLS-1$ //default fStyleSheetText.setEnabled(false); fStyleSheetBrowseButton.setEnabled(false); } else { fStyleSheetButton.setSelection(true); fStyleSheetText.setText(str); } //Listeners fStyleSheetButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fStyleSheetText, fStyleSheetBrowseButton }) { public void validate() { doValidation(STYLESHEETSTATUS); } }); fStyleSheetText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(STYLESHEETSTATUS); } }); fStyleSheetBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleFileBrowseButtonPressed(fStyleSheetText, new String[] { "*.css" }, JavadocExportMessages.getString("JavadocSpecificsWizardPage.stylesheetbrowsedialog.title")); //$NON-NLS-1$ //$NON-NLS-2$ } }); } private void createListDialogField(Composite composite) { Composite c= new Composite(composite, SWT.NONE); c.setLayout(createGridLayout(3)); c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL, 4, 0)); ((GridLayout) c.getLayout()).marginWidth= 0; String[] buttonlabels= new String[] { JavadocExportMessages.getString("JavadcoStandardWizardPage.selectallbutton.label"), JavadocExportMessages.getString("JavadcoStandardWizardPage.clearallbutton.label"), JavadocExportMessages.getString("JavadocStandardWizardPage.configurebutton.label")}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ JavadocLinkDialogLabelProvider labelProvider= new JavadocLinkDialogLabelProvider(); fListDialogField= new CheckedListDialogField(new ListAdapter(), buttonlabels, labelProvider); fListDialogField.setCheckAllButtonIndex(0); fListDialogField.setUncheckAllButtonIndex(1); createLabel(c, SWT.NONE, JavadocExportMessages.getString("JavadcoStandardWizardPage.referencedclasses.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 4, 0)); //$NON-NLS-1$ fListDialogField.doFillIntoGrid(c, 3); LayoutUtil.setHorizontalGrabbing(fListDialogField.getListControl(null)); fListDialogField.enableButton(2, false); fTempLinks= createTempLinksStore(); updateCheckedListGroup(); } private Map createTempLinksStore() { Map temp= new HashMap(); IProject[] projects= fStore.getRoot().getProjects(); for (int i= 0; i < projects.length; i++) { IProject iProject= projects[i]; IJavaProject javaProject= JavaCore.create(iProject); if (javaProject != null) { String links= fStore.getLinks(javaProject); temp.put(javaProject, links); } } return temp; } private void checkListDialogFieldElements(List referencedClasses, IJavaProject[] projects) { List checkedElements= new ArrayList(); for (int i= 0; i < projects.length; i++) { IJavaProject iJavaProject= projects[i]; String hrefs= (String) fTempLinks.get(iJavaProject); URL url= null; if (!hrefs.equals("")) { //$NON-NLS-1$ for (Iterator iterator= referencedClasses.iterator(); iterator.hasNext();) { IJavaElement element= (IJavaElement) iterator.next(); try { url= JavaDocLocations.getJavadocBaseLocation(element); } catch (JavaModelException e) { JavaPlugin.log(e); continue; } StringTokenizer tokenizer= new StringTokenizer(hrefs, ";"); //$NON-NLS-1$ while (tokenizer.hasMoreElements()) { String href= (String) tokenizer.nextElement(); if ((url != null) && href.equals(url.toExternalForm())) { if (!checkedElements.contains(element)) checkedElements.add(element); break; } } } } } fListDialogField.setCheckedElements(checkedElements); } private void findRE(List referencedClasses, IJavaProject[] jprojects, List visisted) throws JavaModelException { for (int j= 0; j < jprojects.length; j++) { IJavaProject iJavaProject= jprojects[j]; findReferencedElements(referencedClasses, iJavaProject, new ArrayList()); } } /** * Method finds a list of all referenced libararies and projects. * */ private void findReferencedElements(List referencedClasses, IJavaProject jproject, List visited) throws JavaModelException { //to avoid loops if (visited.contains(jproject)) { return; } visited.add(jproject); IClasspathEntry[] entries= jproject.getResolvedClasspath(true); for (int i= 0; i < entries.length; i++) { IClasspathEntry curr= entries[i]; switch (curr.getEntryKind()) { case IClasspathEntry.CPE_LIBRARY : IPackageFragmentRoot el= jproject.getPackageFragmentRoot(curr.getPath().toOSString()); if (el != null) { if (!referencedClasses.contains(el)) { referencedClasses.add(el); } } break; case IClasspathEntry.CPE_PROJECT : IProject reqProject= (IProject) fStore.getRoot().findMember(curr.getPath()); IJavaProject javaProject= JavaCore.create(reqProject); if (reqProject.isOpen()) { if (!referencedClasses.contains(javaProject)) { if (!fWizard.getSelectedProjects().contains(javaProject)) referencedClasses.add(javaProject); findReferencedElements(referencedClasses, javaProject, visited); } } break; } } } private void doValidation(int VALIDATE) { File file= null; String ext= null; Path path= null; switch (VALIDATE) { case STYLESHEETSTATUS : fStyleSheetStatus= new StatusInfo(); if (fStyleSheetButton.getSelection()) { path= new Path(fStyleSheetText.getText()); file= new File(fStyleSheetText.getText()); ext= path.getFileExtension(); if ((file == null) || !file.exists()) { fStyleSheetStatus.setError(JavadocExportMessages.getString("JavadcoStandardWizardPage.stylesheetnopath.error")); //$NON-NLS-1$ } else if ((ext == null) || !ext.equalsIgnoreCase("css")) { //$NON-NLS-1$ fStyleSheetStatus.setError(JavadocExportMessages.getString("JavadcoStandardWizardPage.stylesheetnotcss.error")); //$NON-NLS-1$ } } break; } updateStatus(findMostSevereStatus()); } private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fStyleSheetStatus }); } protected void finish() { if (fTitleButton.getSelection()) fStore.setTitle(fTitleText.getText()); else fStore.setTitle(""); //$NON-NLS-1$ //don't store the buttons if they are not enabled //this will change when there is a single page aimed at the standard doclet if (true) { Object[] buttons= fButtonsList.toArray(); for (int i= 0; i < buttons.length; i++) { FlaggedButton button= (FlaggedButton) buttons[i]; if (button.getButton().getEnabled()) fStore.setBoolean(button.getFlag(), !(button.getButton().getSelection() ^ button.show())); else fStore.setBoolean(button.getFlag(), false == button.show()); } } if (fStyleSheetText.getEnabled()) fStore.setStyleSheet(fStyleSheetText.getText()); else fStore.setStyleSheet(""); //$NON-NLS-1$ String hrefs= makeHrefString(); fStore.setDependencies(hrefs); //only store the new dependecies for a project if only one is selected if (fWizard.getSelectedProjects().size() == 1) fStore.setLinks((IJavaProject) fWizard.getSelectedProjects().get(0), hrefs); } protected String makeHrefString() { boolean firstTime= true; StringBuffer buf= new StringBuffer(); List els= fListDialogField.getCheckedElements(); URL url= null; for (Iterator iterator= els.iterator(); iterator.hasNext();) { try { IJavaElement element= (IJavaElement) iterator.next(); url= JavaDocLocations.getJavadocBaseLocation(element); } catch (JavaModelException e) { JavaPlugin.log(e); continue; } if (url != null) { if (firstTime) firstTime= false; else buf.append(";"); //$NON-NLS-1$ buf.append(url.toExternalForm()); } } return buf.toString(); } //get the links public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { doValidation(STYLESHEETSTATUS); //update elements CheckedListDialogField updateCheckedListGroup(); } else { String hrefs= makeHrefString(); IJavaProject[] projects= (IJavaProject[]) fWizard.getSelectedProjects().toArray(new IJavaProject[fWizard.getSelectedProjects().size()]); for (int i= 0; i < projects.length; i++) { fTempLinks.put(projects[i], hrefs); } } } /** * Method will refresh the list of referenced libraries and projects * depended on the projects or elements of projects selected in the * TreeViewer on the JavadocTreeWizardPage. */ public void updateCheckedListGroup() { List referencedClasses= new ArrayList(); List visited= new ArrayList(); try { IJavaProject[] currProjects= (IJavaProject[]) fWizard.getSelectedProjects().toArray(new IJavaProject[fWizard.getSelectedProjects().size()]); findRE(referencedClasses, currProjects, visited); fListDialogField.removeAllElements(); fListDialogField.addElements(referencedClasses); //compare with elements in list with those that are checked. checkListDialogFieldElements(referencedClasses, currProjects); } catch (JavaModelException e) { JavaPlugin.log(e); } } public void init() { updateStatus(new StatusInfo()); } protected class FlaggedButton { private Button fButton; private String fFlag; private boolean fShowFlag; public FlaggedButton(Composite composite, String message, GridData gridData, String flag, boolean show) { fFlag= flag; fShowFlag= show; fButton= createButton(composite, SWT.CHECK, message, gridData); fButtonsList.add(this); setButtonSettings(); } public Button getButton() { return fButton; } public String getFlag() { return fFlag; } public boolean show() { return fShowFlag; } private void setButtonSettings() { fButton.setSelection(!(fStore.getBoolean(fFlag) ^ fShowFlag)); } } //end class FlaggesButton private class ListAdapter implements IListAdapter { /** * @see IListAdapter#customButtonPressed(DialogField, int) */ public void customButtonPressed(DialogField field, int index) { if (index == 2) doEditButtonPressed(); } /** * @see IListAdapter#selectionChanged(DialogField) */ public void selectionChanged(DialogField field) { List selection= fListDialogField.getSelectedElements(); if (selection.size() != 1) { fListDialogField.enableButton(2, false); } else { fListDialogField.enableButton(2, true); } } } /** * Method doEditButtonPressed. */ private void doEditButtonPressed() { StructuredSelection selection= (StructuredSelection) fListDialogField.getTableViewer().getSelection(); Object obj= selection.getFirstElement(); if (obj instanceof IAdaptable) { IJavaElement el= (IJavaElement) ((IAdaptable) obj).getAdapter(IJavaElement.class); JavadocPropertyDialog jdialog= new JavadocPropertyDialog(getShell(), el); jdialog.open(); } } private class JavadocPropertyDialog extends StatusDialog implements IStatusChangeListener { private JavadocConfigurationBlock fJavadocConfigurationBlock; private IJavaElement fElement; public JavadocPropertyDialog(Shell parent, IJavaElement selection) { super(parent); setTitle(JavadocExportMessages.getString("JavadocStandardWizardPage.javadocpropertydialog.title")); //$NON-NLS-1$ fJavadocConfigurationBlock= new JavadocConfigurationBlock(selection, parent, this); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); Control inner= fJavadocConfigurationBlock.createContents(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } public void statusChanged(IStatus status) { updateStatus(status); } /** * @see Dialog#okPressed() */ protected void okPressed() { fJavadocConfigurationBlock.performOk(); super.okPressed(); fListDialogField.refresh(); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.JAVADOC_PROPERTY_DIALOG); } } }
26,354
Bug 26354 Errors Deleting packages in PackageExplorer
null
resolved fixed
9cc0e77
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-14T17:33:13Z
2002-11-14T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageFragmentProvider.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.AppearancePreferencePage; /** * Content provider which provides package fragments for hierarchical * Package Explorer layout. * * @since 2.1 */ public class PackageFragmentProvider implements IPropertyChangeListener, ITreeContentProvider, IElementChangedListener{ private TreeViewer fViewer; private boolean fFoldPackages; public PackageFragmentProvider() { fFoldPackages= AppearancePreferencePage.arePackagesFoldedInHierarchicalLayout(); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(Object) */ public Object[] getChildren(Object parentElement) { try { if (parentElement instanceof IJavaElement) { IJavaElement iJavaElement= (IJavaElement) parentElement; int type= iJavaElement.getElementType(); switch (type) { case IJavaElement.JAVA_PROJECT: { IJavaProject project= (IJavaProject)iJavaElement; IProject proj= project.getProject(); List children= new ArrayList(); IPackageFragmentRoot defaultroot= project.getPackageFragmentRoot(proj); if(defaultroot.exists()){ IJavaElement[] els= defaultroot.getChildren(); children= getTopLevelChildrenByElementName(els); } return filter(children.toArray()); } case IJavaElement.PACKAGE_FRAGMENT_ROOT : { IPackageFragmentRoot root = (IPackageFragmentRoot) parentElement; if (root.exists()) { IResource resource = root.getUnderlyingResource(); if (root.isArchive()) { IJavaElement[] els = root.getChildren(); return filter(getTopLevelChildrenByElementName(els).toArray()); } else if (resource instanceof IFolder) { IFolder folder = (IFolder) resource; IResource[] reses = folder.members(); List children = getFolders(reses); IPackageFragment defaultPackage= root.getPackageFragment(""); //$NON-NLS-1$ if(defaultPackage.exists()) children.add(defaultPackage); return filter(children.toArray()); } } break; } case IJavaElement.PACKAGE_FRAGMENT : { IPackageFragment packageFragment = (IPackageFragment) parentElement; if (!packageFragment.isDefaultPackage()) { IResource resource = packageFragment.getUnderlyingResource(); if (resource != null && resource instanceof IFolder) { IFolder folder = (IFolder) resource; IResource[] reses = folder.members(); Object[] children = getFolders(reses).toArray(); return filter(children); //if the resource is null, maybe member of an archive } else { IJavaElement parent = packageFragment.getParent(); if (parent instanceof IPackageFragmentRoot) { IPackageFragmentRoot root = (IPackageFragmentRoot) parent; Object[] children = findNextLevelChildrenByElementName(root, packageFragment); return filter(children); } } } break; } default : // do nothing } } } catch (JavaModelException e) { JavaPlugin.log(e); } catch (CoreException e) { JavaPlugin.log(e); } return new Object[0]; } private Object[] filter(Object[] children) { if (fFoldPackages) { for (int i = 0; i < children.length; i++) { if (children[i] instanceof IPackageFragment) { IPackageFragment fragment = (IPackageFragment) children[i]; if(!fragment.isDefaultPackage()) children[i] = getBottomPackage(fragment); } } } return children; } private Object getBottomPackage(IPackageFragment iPackageFragment) { try { if(isEmpty(iPackageFragment)) return findChildrenToBeCompounded(iPackageFragment); } catch (JavaModelException e) { JavaPlugin.log(e); } return iPackageFragment; } private IPackageFragment findChildrenToBeCompounded(IPackageFragment fragment) throws JavaModelException { Object[] children = getChildren(fragment); if ((children.length == 1) && (children[0] instanceof IPackageFragment)) { if (isEmpty((IPackageFragment) children[0])) return findChildrenToBeCompounded((IPackageFragment) children[0]); else return (IPackageFragment)children[0]; } return fragment; } private boolean isEmpty(IPackageFragment fragment) throws JavaModelException { return (!fragment.containsJavaResources()) && (fragment.getNonJavaResources().length==0); } private Object[] findNextLevelChildrenByElementName(IPackageFragmentRoot parent, IPackageFragment fragment) { List list= new ArrayList(); try { IJavaElement[] children= parent.getChildren(); String fragmentname= fragment.getElementName(); for (int i= 0; i < children.length; i++) { IJavaElement element= children[i]; if (element instanceof IPackageFragment) { IPackageFragment frag= (IPackageFragment) element; String name= element.getElementName(); if (!"".equals(fragmentname) && name.startsWith(fragmentname) && !name.equals(fragmentname)) { //$NON-NLS-1$ String tail= name.substring(fragmentname.length() + 1); if (!"".equals(tail) && (tail.indexOf(".") == -1)) {//$NON-NLS-1$ //$NON-NLS-2$ list.add(frag); } } } } } catch (JavaModelException e) { JavaPlugin.log(e); } return list.toArray(); } private List getTopLevelChildrenByElementName(IJavaElement[] elements){ List topLevelElements= new ArrayList(); for (int i= 0; i < elements.length; i++) { IJavaElement iJavaElement= elements[i]; //if the name of the PackageFragment is the top level package it will contain no "." separators if((iJavaElement.getElementName().indexOf(".")==-1) && (iJavaElement instanceof IPackageFragment)){ //$NON-NLS-1$ topLevelElements.add(iJavaElement); } } return topLevelElements; } private List getFolders(IResource[] resources) throws JavaModelException { List list= new ArrayList(); for (int i= 0; i < resources.length; i++) { IResource resource= resources[i]; if (resource instanceof IFolder) { IFolder folder= (IFolder) resource; IJavaElement element= JavaCore.create(folder); if (element instanceof IPackageFragment) { list.add(element); } } } return list; } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(Object) */ public Object getParent(Object element) { if (element instanceof IPackageFragment) { IPackageFragment frag = (IPackageFragment) element; //@Changed: a fix, before: if(frag.exists() && isEmpty(frag)) return filterParent(getActualParent(frag)); } return null; } public Object getActualParent(IPackageFragment fragment) { try { if (fragment.exists()) { IJavaElement parent = fragment.getParent(); if ((parent instanceof IPackageFragmentRoot) && parent.exists()) { IPackageFragmentRoot root = (IPackageFragmentRoot) parent; if (root.isArchive()) { return findNextLevelChildrenByElementName(fragment, root); } else { IResource resource = fragment.getUnderlyingResource(); if ((resource != null) && (resource instanceof IFolder)) { IFolder folder = (IFolder) resource; IResource res = folder.getParent(); IJavaElement el = JavaCore.create(res); return el; } } return parent; } } } catch (JavaModelException e) { JavaPlugin.log(e); } return null; } private Object filterParent(Object parent) { if (fFoldPackages && (parent!=null)) { try { if (parent instanceof IPackageFragment) { IPackageFragment fragment = (IPackageFragment) parent; if (isEmpty(fragment) && hasSingleChild(fragment)) { return filterParent(getActualParent(fragment)); } } } catch (JavaModelException e) { JavaPlugin.log(e); } } return parent; } private boolean hasSingleChild(IPackageFragment fragment) { return getChildren(fragment).length==1; } private Object findNextLevelChildrenByElementName(IJavaElement child, IPackageFragmentRoot parent) { String name= child.getElementName(); if(name.indexOf(".")==-1) //$NON-NLS-1$ return parent; try { String realParentName= child.getElementName().substring(0,name.lastIndexOf(".")); //$NON-NLS-1$ IJavaElement[] children= parent.getChildren(); for (int i= 0; i < children.length; i++) { IJavaElement element= children[i]; if(element.getElementName().equals(realParentName)) return element; } } catch (JavaModelException e) { JavaPlugin.log(e); } return parent; } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(Object) */ public boolean hasChildren(Object element) { if (element instanceof IPackageFragment) { IPackageFragment fragment= (IPackageFragment) element; if(fragment.isDefaultPackage()) return false; } return getChildren(element).length > 0; } /* * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(Object) */ public Object[] getElements(Object inputElement) { return getChildren(inputElement); } /* * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ public void dispose() { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); } /** * Called when the view is closed and opened. * * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(Viewer, Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { fViewer= (TreeViewer)viewer; } /* * @see org.eclipse.jdt.core.IElementChangedListener#elementChanged(org.eclipse.jdt.core.ElementChangedEvent) */ public void elementChanged(ElementChangedEvent event) { processDelta(event.getDelta()); } public void processDelta(IJavaElementDelta delta) { int kind = delta.getKind(); final IJavaElement element = delta.getElement(); if (element instanceof IPackageFragment) { if (kind == IJavaElementDelta.REMOVED) { postRunnable(new Runnable() { public void run() { Control ctrl = fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.setRedraw(false); if (!fFoldPackages) ((TreeViewer) fViewer).remove(element); else refreshGrandParent(element); ctrl.setRedraw(true); } } }); return; } else if (kind == IJavaElementDelta.ADDED) { final Object parent = getParent(element); if (parent != null) { postRunnable(new Runnable() { public void run() { Control ctrl = fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.setRedraw(false); if (!fFoldPackages) ((TreeViewer) fViewer).add(parent, element); else refreshGrandParent(element); ctrl.setRedraw(true); } } }); } return; } else if (kind == IJavaElementDelta.CHANGED) { postRunnable(new Runnable() { public void run() { Control ctrl = fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.setRedraw(false); refreshGrandParent(element); ctrl.setRedraw(true); } } }); return; } } IJavaElementDelta[] affectedChildren = delta.getAffectedChildren(); processAffectedChildren(affectedChildren); } // XXX: needs to be revisited - might be a performance issue private void refreshGrandParent(final IJavaElement element) { Object gp= getGrandParent(element); if (gp instanceof IJavaElement) { IJavaElement el = (IJavaElement) gp; if(el.exists()) fViewer.refresh(gp); } return; } private Object getGrandParent(IJavaElement element) { Object object= getParent(element); if((object!=null) && (object instanceof IPackageFragment)) { IPackageFragment frag= (IPackageFragment)object; if(frag.exists()) return getParent(object); } return object; } protected void processAffectedChildren(IJavaElementDelta[] affectedChildren) { for (int i= 0; i < affectedChildren.length; i++) { if (!(affectedChildren[i] instanceof ICompilationUnit)) { processDelta(affectedChildren[i]); } } } private void postRunnable(final Runnable r) { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { Display currentDisplay= Display.getCurrent(); if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay())) ctrl.getDisplay().syncExec(r); else ctrl.getDisplay().asyncExec(r); } } /* * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if(AppearancePreferencePage.arePackagesFoldedInHierarchicalLayout()!=fFoldPackages){ fFoldPackages= AppearancePreferencePage.arePackagesFoldedInHierarchicalLayout(); fViewer.getControl().setRedraw(false); Object[] expandedObjects= fViewer.getExpandedElements(); fViewer.refresh(); fViewer.setExpandedElements(expandedObjects); fViewer.getControl().setRedraw(true); } } }
26,289
Bug 26289 JUnit: Exceptions when add new JUnit launch config
Build 20021113 1. Create Java project called JUnit and import JUnit 2. Press Run... from running man button 3. Select JUnit and press New 4. Press Search ==> nothing happens except an exception being written to .log (see attached file)
resolved fixed
7a38577
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-14T17:51:53Z
2002-11-14T13:20:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitMainTab.java
package org.eclipse.jdt.internal.junit.launcher; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.junit.ui.JUnitMessages; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.SelectionDialog; /** * This tab appears in the LaunchConfigurationDialog for launch configurations that * require Java-specific launching information such as a main type and JRE. */ public class JUnitMainTab extends JUnitLaunchConfigurationTab { // Project UI widgets private Label fProjLabel; private Text fProjText; private Button fProjButton; private Button fKeepRunning; // Test class UI widgets private Label fTestLabel; private Text fTestText; private Button fSearchButton; private final Image fTestIcon= createImage("obj16/test.gif"); private Text fContainerText; private IJavaElement fContainerElement; private Button fContainerSearchButton; private Button fTestContainerRadioButton; private Button fTestRadioButton; /** * @see ILaunchConfigurationTab#createControl(TabItem) */ public void createControl(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); setControl(comp); GridLayout topLayout = new GridLayout(); topLayout.numColumns= 2; comp.setLayout(topLayout); new Label(comp, SWT.NONE); createProjectGroup(comp); createTestSelectionGroup(comp); createTestContainerSelectionGroup(comp); createKeepAliveGroup(comp); } private void createTestContainerSelectionGroup(Composite comp) { GridData gd; fTestContainerRadioButton= new Button(comp, SWT.RADIO); fTestContainerRadioButton.setText("All Tests in Project, Source Folder or Package:"); gd = new GridData(); gd.horizontalSpan = 2; fTestContainerRadioButton.setLayoutData(gd); fTestContainerRadioButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (fTestContainerRadioButton.getSelection()) { testModeChanged(); fTestText.setText(""); } } public void widgetDefaultSelected(SelectionEvent e) { } }); fContainerText = new Text(comp, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= 20; fContainerText.setLayoutData(gd); fContainerText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); } }); fContainerSearchButton = new Button(comp, SWT.PUSH); fContainerSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$ fContainerSearchButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { handleContainerSearchButtonSelected(); } }); setButtonGridData(fContainerSearchButton); } private void handleContainerSearchButtonSelected() { IJavaElement javaElement= chooseContainer(fContainerElement); if (javaElement != null) { fContainerElement= javaElement; fContainerText.setText(javaElement.getElementName()); } } public void createKeepAliveGroup(Composite comp) { GridData gd; fKeepRunning = new Button(comp, SWT.CHECK); fKeepRunning.setText(JUnitMessages.getString("JUnitMainTab.label.keeprunning")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.horizontalSpan= 2; fKeepRunning.setLayoutData(gd); } public void createTestSelectionGroup(Composite comp) { GridData gd; fTestRadioButton= new Button(comp, SWT.RADIO /*| SWT.LEFT*/); fTestRadioButton.setText(JUnitMessages.getString("JUnitMainTab.label.test")); gd = new GridData(); gd.horizontalSpan = 2; fTestRadioButton.setLayoutData(gd); fTestRadioButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (fTestRadioButton.getSelection()) { testModeChanged(); fContainerText.setText(""); fContainerElement= null; } } public void widgetDefaultSelected(SelectionEvent e) { } }); fTestText = new Text(comp, SWT.SINGLE | SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= 20; fTestText.setLayoutData(gd); fTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); } }); fSearchButton = new Button(comp, SWT.PUSH); fSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$ fSearchButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { handleSearchButtonSelected(); } }); setButtonGridData(fSearchButton); } public void createProjectGroup(Composite comp) { GridData gd; fProjLabel = new Label(comp, SWT.NONE); fProjLabel.setText(JUnitMessages.getString("JUnitMainTab.label.project")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan = 2; fProjLabel.setLayoutData(gd); fProjText= new Text(comp, SWT.SINGLE | SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); fProjText.setLayoutData(gd); fProjText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { updateLaunchConfigurationDialog(); } }); fProjButton = new Button(comp, SWT.PUSH); fProjButton.setText(JUnitMessages.getString("JUnitMainTab.label.browse")); //$NON-NLS-1$ fProjButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { handleProjectButtonSelected(); } }); setButtonGridData(fProjButton); } protected static Image createImage(String path) { try { ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path)); return id.createImage(); } catch (MalformedURLException e) { // fall through } return null; } /** * @see ILaunchConfigurationTab#initializeFrom(ILaunchConfiguration) */ public void initializeFrom(ILaunchConfiguration config) { updateProjectFromConfig(config); String containerHandle= ""; try { containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ } catch (CoreException ce) { } if (containerHandle.length() > 0) updateTestContainerFromConfig(config); else updateTestTypeFromConfig(config); updateKeepRunning(config); } private void updateKeepRunning(ILaunchConfiguration config) { boolean running= false; try { running= config.getAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, false); } catch (CoreException ce) { } fKeepRunning.setSelection(running); } protected void updateProjectFromConfig(ILaunchConfiguration config) { String projectName= ""; //$NON-NLS-1$ try { projectName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ } catch (CoreException ce) { } fProjText.setText(projectName); } protected void updateTestTypeFromConfig(ILaunchConfiguration config) { String testTypeName= ""; //$NON-NLS-1$ try { testTypeName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$ } catch (CoreException ce) { } fTestRadioButton.setSelection(true); setEnableSingleTestGroup(true); setEnableContainerTestGroup(false); fTestContainerRadioButton.setSelection(false); fTestText.setText(testTypeName); fContainerText.setText(""); } protected void updateTestContainerFromConfig(ILaunchConfiguration config) { String containerHandle= ""; try { containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ if (containerHandle.length() > 0) { fContainerElement= JavaCore.create(containerHandle); } } catch (CoreException ce) { } fTestContainerRadioButton.setSelection(true); setEnableSingleTestGroup(false); setEnableContainerTestGroup(true); fTestRadioButton.setSelection(false); if (fContainerElement != null) fContainerText.setText(fContainerElement.getElementName()); fTestText.setText(""); } /** * @see ILaunchConfigurationTab#performApply(ILaunchConfigurationWorkingCopy) */ public void performApply(ILaunchConfigurationWorkingCopy config) { config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)fProjText.getText()); if (fTestContainerRadioButton.getSelection() && fContainerElement != null) config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, fContainerElement.getHandleIdentifier()); else config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)fTestText.getText()); config.setAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, fKeepRunning.getSelection()); } /** * @see ILaunchConfigurationTab#dispose() */ public void dispose() { super.dispose(); fTestIcon.dispose(); } /** * @see AbstractLaunchConfigurationTab#getImage() */ public Image getImage() { return fTestIcon; } /** * Show a dialog that lists all main types */ protected void handleSearchButtonSelected() { Shell shell = getShell(); IJavaProject javaProject = getJavaProject(); SelectionDialog dialog = new TestSelectionDialog(shell, new ProgressMonitorDialog(shell), javaProject); dialog.setTitle(JUnitMessages.getString("JUnitMainTab.testdialog.title")); //$NON-NLS-1$ dialog.setMessage(JUnitMessages.getString("JUnitMainTab.testdialog.message")); //$NON-NLS-1$ if (dialog.open() == SelectionDialog.CANCEL) { return; } Object[] results = dialog.getResult(); if ((results == null) || (results.length < 1)) { return; } IType type = (IType)results[0]; if (type != null) { fTestText.setText(type.getFullyQualifiedName()); javaProject = type.getJavaProject(); fProjText.setText(javaProject.getElementName()); } } /** * Show a dialog that lets the user select a project. This in turn provides * context for the main type, allowing the user to key a main type name, or * constraining the search for main types to the specified project. */ protected void handleProjectButtonSelected() { IJavaProject project = chooseJavaProject(); if (project == null) { return; } String projectName = project.getElementName(); fProjText.setText(projectName); } /** * Realize a Java Project selection dialog and return the first selected project, * or null if there was none. */ protected IJavaProject chooseJavaProject() { IJavaProject[] projects; try { projects= JavaCore.create(getWorkspaceRoot()).getJavaProjects(); } catch (JavaModelException e) { JUnitPlugin.log(e.getStatus()); projects= new IJavaProject[0]; } ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider); dialog.setTitle(JUnitMessages.getString("JUnitMainTab.projectdialog.title")); //$NON-NLS-1$ dialog.setMessage(JUnitMessages.getString("JUnitMainTab.projectdialog.message")); //$NON-NLS-1$ dialog.setElements(projects); IJavaProject javaProject = getJavaProject(); if (javaProject != null) { dialog.setInitialSelections(new Object[] { javaProject }); } if (dialog.open() == ElementListSelectionDialog.OK) { return (IJavaProject) dialog.getFirstResult(); } return null; } /** * Return the IJavaProject corresponding to the project name in the project name * text field, or null if the text does not match a project name. */ protected IJavaProject getJavaProject() { String projectName = fProjText.getText().trim(); if (projectName.length() < 1) { return null; } return getJavaModel().getJavaProject(projectName); } /** * Convenience method to get the workspace root. */ private IWorkspaceRoot getWorkspaceRoot() { return ResourcesPlugin.getWorkspace().getRoot(); } /** * Convenience method to get access to the java model. */ private IJavaModel getJavaModel() { return JavaCore.create(getWorkspaceRoot()); } /** * @see ILaunchConfigurationTab#isValid(ILaunchConfiguration) */ public boolean isValid(ILaunchConfiguration config) { setErrorMessage(null); setMessage(null); String projectName = fProjText.getText().trim(); if (projectName.length() > 0) { if (!ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).exists()) { setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.projectnotexists")); //$NON-NLS-1$ return false; } } String testName = fTestText.getText().trim(); if (testName.length() == 0 && fContainerElement == null) { setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.testnotdefined")); //$NON-NLS-1$ return false; } // TO DO should verify that test exists return true; } private void testModeChanged() { boolean isSingleTestMode= fTestRadioButton.getSelection(); setEnableSingleTestGroup(isSingleTestMode); setEnableContainerTestGroup(!isSingleTestMode); } private void setEnableContainerTestGroup(boolean enabled) { fContainerSearchButton.setEnabled(enabled); fContainerText.setEnabled(enabled); } private void setEnableSingleTestGroup(boolean enabled) { fSearchButton.setEnabled(enabled); fTestText.setEnabled(enabled); } /** * @see ILaunchConfigurationTab#setDefaults(ILaunchConfigurationWorkingCopy) */ public void setDefaults(ILaunchConfigurationWorkingCopy config) { IJavaElement javaElement = getContext(); if (javaElement != null) { initializeJavaProject(javaElement, config); } else { // We set empty attributes for project & main type so that when one config is // compared to another, the existence of empty attributes doesn't cause an // incorrect result (the performApply() method can result in empty values // for these attributes being set on a config if there is nothing in the // corresponding text boxes) config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ } initializeTestAttributes(javaElement, config); } private void initializeTestAttributes(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) { if (javaElement.getElementType() < IJavaElement.COMPILATION_UNIT) initializeTestContainer(javaElement, config); else initializeTestType(javaElement, config); } private void initializeTestContainer(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) { config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, javaElement.getHandleIdentifier()); initializeName(config, javaElement.getElementName()); } private void initializeName(ILaunchConfigurationWorkingCopy config, String name) { if (name == null) { name= ""; } if (name.length() > 0) { int index = name.lastIndexOf('.'); if (index > 0) { name = name.substring(index + 1); } name= getLaunchConfigurationDialog().generateName(name); config.rename(name); } } /** * Set the main type & name attributes on the working copy based on the IJavaElement */ protected void initializeTestType(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) { String name= ""; //$NON-NLS-1$ try { // we only do a search for compilation units or class files or // or source references if ((javaElement instanceof ICompilationUnit) || (javaElement instanceof ISourceReference) || (javaElement instanceof IClassFile)) { IType[] types = TestSearchEngine.findTests(new BusyIndicatorRunnableContext(), new Object[] {javaElement}); if ((types == null) || (types.length < 1)) { return; } // Simply grab the first main type found in the searched element name = types[0].getFullyQualifiedName(); } } catch (InterruptedException ie) { } catch (InvocationTargetException ite) { } if (name == null) name= ""; config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, name); initializeName(config, name); } /** * @see ILaunchConfigurationTab#getName() */ public String getName() { return JUnitMessages.getString("JUnitMainTab.tab.label"); //$NON-NLS-1$ } private IJavaElement chooseContainer(IJavaElement initElement) { Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) { public boolean isSelectedValid(Object element) { return true; } }; acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { public boolean select(Viewer viewer, Object parent, Object element) { return super.select(viewer, parent, element); } }; StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider(); ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider); dialog.setValidator(validator); dialog.setSorter(new JavaElementSorter()); dialog.setTitle("Folder Selection"); dialog.setMessage("Choose a Project, Source Folder or Package:"); dialog.addFilter(filter); dialog.setInput(JavaCore.create(getWorkspaceRoot())); dialog.setInitialSelection(initElement); dialog.setAllowMultiple(false); if (dialog.open() == ElementTreeSelectionDialog.OK) { Object element= dialog.getFirstResult(); return (IJavaElement)element; } return null; } }
26,377
Bug 26377 Editor copy/paste not working when replacing code
Build 20021114 Attempting to replace some text with clipboard content, it ends up overriding the prefix of the target text only (target is larger than clipboard): select 'argSlotSize' and paste it over selected word argSlotSizeze . It will leave some of the selected word in. testcase: package p; public class Y { static void y(){ int argSlotSize = 1; argSlotSizeze += 2; } }
resolved fixed
7c5bb4e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-14T18:00:26Z
2002-11-14T18:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Iterator; import java.util.NoSuchElementException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; /** * Auto indent strategy sensitive to brackets. */ public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy { public JavaAutoIndentStrategy() { } // evaluate the line with the opening bracket that matches the closing bracket on the given line protected int findMatchingOpenBracket(IDocument d, int line, int end, int closingBracketIncrease) throws BadLocationException { int start= d.getLineOffset(line); int brackcount= getBracketCount(d, start, end, false) - closingBracketIncrease; // sum up the brackets counts of each line (closing brackets count negative, // opening positive) until we find a line the brings the count to zero while (brackcount < 0) { line--; if (line < 0) { return -1; } start= d.getLineOffset(line); end= start + d.getLineLength(line) - 1; brackcount += getBracketCount(d, start, end, false); } return line; } private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException { int bracketcount= 0; while (start < end) { char curr= d.getChar(start); start++; switch (curr) { case '/' : if (start < end) { char next= d.getChar(start); if (next == '*') { // a comment starts, advance to the comment end start= getCommentEnd(d, start + 1, end); } else if (next == '/') { // '//'-comment: nothing to do anymore on this line start= end; } } break; case '*' : if (start < end) { char next= d.getChar(start); if (next == '/') { // we have been in a comment: forget what we read before bracketcount= 0; start++; } } break; case '{' : bracketcount++; ignoreCloseBrackets= false; break; case '}' : if (!ignoreCloseBrackets) { bracketcount--; } break; case '"' : case '\'' : start= getStringEnd(d, start, end, curr); break; default : } } return bracketcount; } // ----------- bracket counting ------------------------------------------------------ private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '*') { if (pos < end && d.getChar(pos) == '/') { return pos + 1; } } } return end; } protected String getIndentOfLine(IDocument d, int line) throws BadLocationException { if (line > -1) { int start= d.getLineOffset(line); int end= start + d.getLineLength(line) - 1; int whiteend= findEndOfWhiteSpace(d, start, end); return d.get(start, whiteend - start); } else { return ""; //$NON-NLS-1$ } } private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '\\') { // ignore escaped characters pos++; } else if (curr == ch) { return pos; } } return end; } protected void smartInsertAfterBracket(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); int start= d.getLineOffset(line); int whiteend= findEndOfWhiteSpace(d, start, c.offset); // shift only when line does not contain any text up to the closing bracket if (whiteend == c.offset) { // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1 && indLine != line) { // take the indent of the found line StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine)); // add the rest of the current line including the just added close bracket replaceText.append(d.get(whiteend, c.offset - whiteend)); replaceText.append(c.text); // modify document command c.length += c.offset - start; c.offset= start; c.text= replaceText.toString(); } } } catch (BadLocationException excp) { System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message1")); //$NON-NLS-1$ } } protected void smartIndentAfterNewLine(IDocument d, DocumentCommand c) { int docLength= d.getLength(); if (c.offset == -1 || docLength == 0) return; try { int p= (c.offset == docLength ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); StringBuffer buf= new StringBuffer(c.text); if (c.offset < docLength && d.getChar(c.offset) == '}') { int indLine= findMatchingOpenBracket(d, line, c.offset, 0); if (indLine == -1) { indLine= line; } buf.append(getIndentOfLine(d, indLine)); } else { int start= d.getLineOffset(line); // if line just ended a javadoc comment, take the indent from the comment's begin line IDocumentPartitioner partitioner= d.getDocumentPartitioner(); if (partitioner != null) { ITypedRegion region= partitioner.getPartition(start); if (JavaPartitionScanner.JAVA_DOC.equals(region.getType())) start= d.getLineInformationOfOffset(region.getOffset()).getOffset(); } int whiteend= findEndOfWhiteSpace(d, start, c.offset); buf.append(d.get(start, whiteend - start)); if (getBracketCount(d, start, c.offset, true) > 0) { buf.append(getOneIndentLevel()); } } c.text= buf.toString(); } catch (BadLocationException excp) { System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message2")); //$NON-NLS-1$ } } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { JavaPlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } protected void pasteText(IDocument document, DocumentCommand command) { String lineDelimiter= getLineDelimiter(document); try { String pastedText= command.text; Assert.isNotNull(pastedText); Assert.isTrue(pastedText.length() > 1); String strippedParagraph= stripIndent(pastedText, lineDelimiter); // check selection int offset= command.offset; int line= document.getLineOfOffset(offset); int lineOffset= document.getLineOffset(line); // format String prefix= document.get(lineOffset, offset - lineOffset); String blockIndent= getIndent(document, command); String indent= blockIndent == null ? "" : blockIndent + createIndent(1); //$NON-NLS-1$ // add one indent level boolean formatFirstLine= prefix.trim().length() == 0; String formattedParagraph= format(strippedParagraph, indent, lineDelimiter, formatFirstLine); // paste if (formatFirstLine) command.offset= lineOffset; command.text= formattedParagraph; } catch (BadLocationException e) { JavaPlugin.log(e); } } /** * Returns the displayed width of a string, taking in account the displayed tab width. * The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string) { final int tabWidth= JavaPlugin.getDefault().getPreferenceStore().getInt(JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH); int column= 0; for (int i= 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else column++; return column; } private String getIndent(IDocument d, DocumentCommand c) { if (c.offset < 0) return null; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1 && indLine != line) // take the indent of the found line return getIndentOfLine(d, indLine); } catch (BadLocationException excp) { System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message1")); //$NON-NLS-1$ } return null; } private static final class LineIterator implements Iterator { /** The document to iterator over. */ private final IDocument fDocument; /** The line index. */ private int fLineIndex; /** * Creates a line iterator. */ public LineIterator(String string) { fDocument= new Document(string); } /* * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return fLineIndex != fDocument.getNumberOfLines(); } /* * @see java.util.Iterator#next() */ public Object next() { try { IRegion region= fDocument.getLineInformation(fLineIndex++); return fDocument.get(region.getOffset(), region.getLength()); } catch (BadLocationException e) { JavaPlugin.log(e); throw new NoSuchElementException(); } } /* * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } private static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } private static String createIndent(int level) { StringBuffer buffer= new StringBuffer(); if (CodeFormatterPreferencePage.useSpaces()) { int tabWidth= getPreferenceStore().getInt(JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH); int width= level * tabWidth; for (int i= 0; i != width; ++i) buffer.append(' '); } else { buffer.append('\t'); } return buffer.toString(); } private static String createPrefix(int displayedWidth) { StringBuffer buffer= new StringBuffer(); if (CodeFormatterPreferencePage.useSpaces()) { for (int i= 0; i != displayedWidth; ++i) buffer.append(' '); } else { int tabWidth= getPreferenceStore().getInt(JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH); int div= displayedWidth / tabWidth; int mod= displayedWidth % tabWidth; for (int i= 0; i != div; ++i) buffer.append('\t'); for (int i= 0; i != mod; ++i) buffer.append(' '); } return buffer.toString(); } private String stripIndent(String paragraph, String lineDelimiter) { final StringBuffer buffer= new StringBuffer(); // determine minimum indent width int minIndentWidth= Integer.MAX_VALUE; for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); String trimmedLine= line.trim(); if (trimmedLine.length() == 0) continue; int index= line.indexOf(trimmedLine); String indent= line.substring(0, index); int width= calculateDisplayedWidth(indent); minIndentWidth= Math.min(minIndentWidth, width); } // strip prefixes for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); String trimmedLine= line.trim(); if (trimmedLine.length() != 0) { int index= line.indexOf(trimmedLine); String indent= line.substring(0, index); int width= calculateDisplayedWidth(indent); int strippedWidth= width - minIndentWidth; String prefix= createPrefix(strippedWidth); buffer.append(prefix); buffer.append(trimmedLine); } if (iterator.hasNext()) buffer.append(lineDelimiter); } return buffer.toString(); } private String format(String paragraph, String indent, String lineDelimiter, boolean indentFirstLine) { final StringBuffer buffer= new StringBuffer(); for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); if (indentFirstLine && line.trim().length() != 0) buffer.append(indent); else indentFirstLine= true; buffer.append(line); if (iterator.hasNext()) buffer.append(lineDelimiter); } return buffer.toString(); } private String getOneIndentLevel() { return String.valueOf('\t'); } /** * Returns whether the text ends with one of the given search strings. */ private boolean endsWithDelimiter(IDocument d, String txt) { String[] delimiters= d.getLegalLineDelimiters(); for (int i= 0; i < delimiters.length; i++) { if (txt.endsWith(delimiters[i])) return true; } return false; } private boolean equalsDelimiter(IDocument d, String txt) { String[] delimiters= d.getLegalLineDelimiters(); for (int i= 0; i < delimiters.length; i++) { if (txt.equals(delimiters[i])) return true; } return false; } private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) { if (command.text.charAt(0) == '}') smartInsertAfterBracket(document, command); } /* * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand(IDocument d, DocumentCommand c) { if (c.length == 0 && c.text != null && equalsDelimiter(d, c.text)) smartIndentAfterNewLine(d, c); else if (c.text.length() == 1) smartIndentAfterBlockDelimiter(d, c); else if (c.text.length() > 1 && getPreferenceStore().getBoolean(CompilationUnitEditor.SMART_PASTE)) pasteText(d, c); } }
25,203
Bug 25203 ACC: JUnit gui is not accessible [junit]
1) JUnit GUI is not screen reader accessible (can't read w/ MS Inspect or JAWS) 2) Moderately keyboard accessible........can't move between different areas without the use of the mouse
resolved fixed
9688a3f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-14T23:26:48Z
2002-10-22T15:20:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CounterPanel.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; /** * A panel with counters for the number of Runs, Errors and Failures. */ public class CounterPanel extends Composite { private Label fNumberOfErrors; private Label fNumberOfFailures; private Label fNumberOfRuns; private int fTotal; private final Image fErrorIcon= TestRunnerViewPart.createImage("ovr16/error_ovr.gif"); //$NON-NLS-1$ private final Image fFailureIcon= TestRunnerViewPart.createImage("ovr16/failed_ovr.gif"); //$NON-NLS-1$ public CounterPanel(Composite parent) { super(parent, SWT.WRAP); GridLayout gridLayout= new GridLayout(); gridLayout.numColumns= 9; gridLayout.makeColumnsEqualWidth= false; gridLayout.marginWidth= 0; setLayout(gridLayout); fNumberOfRuns= createLabel(JUnitMessages.getString("CounterPanel.label.runs"), null, " 0/0 "); //$NON-NLS-1$ //$NON-NLS-2$ fNumberOfErrors= createLabel(JUnitMessages.getString("CounterPanel.label.errors"), fErrorIcon, " 0 "); //$NON-NLS-1$ //$NON-NLS-2$ fNumberOfFailures= createLabel(JUnitMessages.getString("CounterPanel.label.failures"), fFailureIcon, " 0 "); //$NON-NLS-1$ //$NON-NLS-2$ addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { disposeIcons(); } }); } void disposeIcons() { fErrorIcon.dispose(); fFailureIcon.dispose(); } private Label createLabel(String name, Image image, String init) { Label label= new Label(this, SWT.NONE); if (image != null) { image.setBackground(label.getBackground()); label.setImage(image); } label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); label= new Label(this, SWT.NONE); label.setText(name); label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); label= new Label(this, SWT.NONE); label.setText(init); label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING)); return label; } public void reset() { fNumberOfErrors.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLACK)); fNumberOfFailures.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLACK)); fNumberOfErrors.setText(" 0 "); //$NON-NLS-1$ fNumberOfFailures.setText(" 0 "); //$NON-NLS-1$ String runString= JUnitMessages.getFormattedString("CounterPanel.runcount", new String[] { Integer.toString(0), Integer.toString(0) }); //$NON-NLS-1$ fNumberOfRuns.setText(runString); fTotal= 0; } public void setTotal(int value) { fTotal= value; } public int getTotal(){ return fTotal; } public void setRunValue(int value) { String runString= JUnitMessages.getFormattedString("CounterPanel.runcount", new String[] { Integer.toString(value), Integer.toString(fTotal) }); //$NON-NLS-1$ fNumberOfRuns.setText(runString); fNumberOfRuns.redraw(); redraw(); } public void setErrorValue(int value) { fNumberOfErrors.setText(Integer.toString(value)); redraw(); } public void setFailureValue(int value) { fNumberOfFailures.setText(Integer.toString(value)); redraw(); } }
25,479
Bug 25479 Open Type Dialog causes CPU to churn
Eclipse 2.0.1 & 2.1, Windows 2000 & Windows NT When I open the Open Type Dialog, my CPU is pegged for as long as the dialog is open. Not sure what it is doing in there, but it seems unlikely that it needs to work that hard just sitting open. -Andrew
resolved fixed
06bf6d2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T11:06:27Z
2002-10-29T00:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TypeSelectionDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.Assert; import org.eclipse.ui.dialogs.FilteredList; import org.eclipse.ui.dialogs.TwoPaneElementSelector; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.internal.corext.util.AllTypesCache; import org.eclipse.jdt.internal.corext.util.TypeInfo; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.StringMatcher; import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider; /** * A dialog to select a type from a list of types. */ public class TypeSelectionDialog extends TwoPaneElementSelector { private static class TypeFilterMatcher implements FilteredList.FilterMatcher { private StringMatcher fMatcher; private StringMatcher fQualifierMatcher; /* * @see FilteredList.FilterMatcher#setFilter(String, boolean) */ public void setFilter(String pattern, boolean ignoreCase, boolean igoreWildCards) { int qualifierIndex= pattern.lastIndexOf("."); //$NON-NLS-1$ // type if (qualifierIndex == -1) { fQualifierMatcher= null; fMatcher= new StringMatcher(adjustPattern(pattern), ignoreCase, igoreWildCards); // qualified type } else { fQualifierMatcher= new StringMatcher(pattern.substring(0, qualifierIndex), ignoreCase, igoreWildCards); fMatcher= new StringMatcher(adjustPattern(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 String adjustPattern(String pattern) { int pos= pattern.indexOf('*'); if (pos == -1) return pattern + '*'; else return pattern; } } /* * A string comparator which is aware of obfuscated code * (type names starting with lower case characters). */ private static class StringComparator implements Comparator { public int compare(Object left, Object right) { String leftString= (String) left; String rightString= (String) right; if (Character.isLowerCase(leftString.charAt(0)) && !Character.isLowerCase(rightString.charAt(0))) return +1; if (Character.isLowerCase(rightString.charAt(0)) && !Character.isLowerCase(leftString.charAt(0))) return -1; int result= leftString.compareToIgnoreCase(rightString); if (result == 0) result= leftString.compareTo(rightString); return result; } } private IRunnableContext fRunnableContext; private IJavaSearchScope fScope; private int fElementKinds; /** * Constructs a type selection dialog. * @param parent the parent shell. * @param context the runnable context. * @param elementKinds <code>IJavaSearchConstants.CLASS</code>, <code>IJavaSearchConstants.INTERFACE</code> * or <code>IJavaSearchConstants.TYPE</code> * @param scope the java search scope. */ public TypeSelectionDialog(Shell parent, IRunnableContext context, int elementKinds, IJavaSearchScope scope) { super(parent, new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeInfoLabelProvider.SHOW_ROOT_POSTFIX)); Assert.isNotNull(context); Assert.isNotNull(scope); fRunnableContext= context; fScope= scope; fElementKinds= elementKinds; setUpperListLabel(JavaUIMessages.getString("TypeSelectionDialog.upperLabel")); //$NON-NLS-1$ setLowerListLabel(JavaUIMessages.getString("TypeSelectionDialog.lowerLabel")); //$NON-NLS-1$ } /* * @see AbstractElementListSelectionDialog#createFilteredList(Composite) */ protected FilteredList createFilteredList(Composite parent) { FilteredList list= super.createFilteredList(parent); fFilteredList.setFilterMatcher(new TypeFilterMatcher()); fFilteredList.setComparator(new StringComparator()); return list; } /* * @see org.eclipse.jface.window.Window#open() */ public int open() { final ArrayList typeList= new ArrayList(); if (AllTypesCache.isCacheUpToDate()) { // run without progress monitor try { AllTypesCache.getTypes(fScope, fElementKinds, null, typeList); } catch (JavaModelException e) { ExceptionHandler.handle(e, JavaUIMessages.getString("TypeSelectionDialog.error2Title"), JavaUIMessages.getString("TypeSelectionDialog.error2Message")); //$NON-NLS-1$ //$NON-NLS-2$ return CANCEL; } } else { IRunnableWithProgress runnable= new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { AllTypesCache.getTypes(fScope, fElementKinds, monitor, typeList); } catch (JavaModelException e) { throw new InvocationTargetException(e); } if (monitor.isCanceled()) { throw new InterruptedException(); } } }; try { fRunnableContext.run(true, true, runnable); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, JavaUIMessages.getString("TypeSelectionDialog.error3Title"), JavaUIMessages.getString("TypeSelectionDialog.error3Message")); //$NON-NLS-1$ //$NON-NLS-2$ return CANCEL; } catch (InterruptedException e) { // cancelled by user return CANCEL; } } if (typeList.isEmpty()) { String title= JavaUIMessages.getString("TypeSelectionDialog.notypes.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.notypes.message"); //$NON-NLS-1$ MessageDialog.openInformation(getShell(), title, message); return CANCEL; } TypeInfo[] typeRefs= (TypeInfo[])typeList.toArray(new TypeInfo[typeList.size()]); setElements(typeRefs); return super.open(); } /** * @see SelectionStatusDialog#computeResult() */ protected void computeResult() { TypeInfo ref= (TypeInfo) getLowerSelectedElement(); if (ref == null) return; try { IType type= ref.resolveType(fScope); if (type == null) { // not a class file or compilation unit String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); setResult(null); } else { List result= new ArrayList(1); result.add(type); setResult(result); } } catch (JavaModelException e) { String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$ String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$ ErrorDialog.openError(getShell(), title, message, e.getStatus()); setResult(null); } } }
26,252
Bug 26252 "Move to Top Level..." fails with stacktrace [refactoring]
I20021113 Performing "Refactor->Move to Top Level..." results in the following stacktrace: java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:106) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 4] Overlapping text edits at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring .createChange(MoveInnerToTopRefactoring.java:277) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:98) ... 1 more
resolved fixed
c09faf4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T15:27:43Z
2002-11-14T10:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test_nonstatic_33/in/A.java
26,252
Bug 26252 "Move to Top Level..." fails with stacktrace [refactoring]
I20021113 Performing "Refactor->Move to Top Level..." results in the following stacktrace: java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:106) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 4] Overlapping text edits at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring .createChange(MoveInnerToTopRefactoring.java:277) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:98) ... 1 more
resolved fixed
c09faf4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T15:27:43Z
2002-11-14T10:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test_nonstatic_33/out/A.java
26,252
Bug 26252 "Move to Top Level..." fails with stacktrace [refactoring]
I20021113 Performing "Refactor->Move to Top Level..." results in the following stacktrace: java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:106) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 4] Overlapping text edits at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring .createChange(MoveInnerToTopRefactoring.java:277) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:98) ... 1 more
resolved fixed
c09faf4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T15:27:43Z
2002-11-14T10:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test_nonstatic_33/out/I.java
26,252
Bug 26252 "Move to Top Level..." fails with stacktrace [refactoring]
I20021113 Performing "Refactor->Move to Top Level..." results in the following stacktrace: java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:106) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 4] Overlapping text edits at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring .createChange(MoveInnerToTopRefactoring.java:277) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:98) ... 1 more
resolved fixed
c09faf4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T15:27:43Z
2002-11-14T10:33:20Z
org.eclipse.jdt.ui.tests.refactoring/test
26,252
Bug 26252 "Move to Top Level..." fails with stacktrace [refactoring]
I20021113 Performing "Refactor->Move to Top Level..." results in the following stacktrace: java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:106) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 4] Overlapping text edits at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring .createChange(MoveInnerToTopRefactoring.java:277) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:98) ... 1 more
resolved fixed
c09faf4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T15:27:43Z
2002-11-14T10:33:20Z
cases/org/eclipse/jdt/ui/tests/refactoring/MoveInnerToTopLevelTests.java
26,252
Bug 26252 "Move to Top Level..." fails with stacktrace [refactoring]
I20021113 Performing "Refactor->Move to Top Level..." results in the following stacktrace: java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:106) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 4] Overlapping text edits at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring .createChange(MoveInnerToTopRefactoring.java:277) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:98) ... 1 more
resolved fixed
c09faf4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T15:27:43Z
2002-11-14T10:33:20Z
org.eclipse.jdt.ui/core
26,252
Bug 26252 "Move to Top Level..." fails with stacktrace [refactoring]
I20021113 Performing "Refactor->Move to Top Level..." results in the following stacktrace: java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:106) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 4] Overlapping text edits at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring .createChange(MoveInnerToTopRefactoring.java:277) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:98) ... 1 more
resolved fixed
c09faf4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T15:27:43Z
2002-11-14T10:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java
25,284
Bug 25284 Open Type Dialog Box doesn't persist new size
Open the Open Type dialog box and resize the window. Close the box and open again, the size isn't remembers.
resolved fixed
fadcaea
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T16:17:10Z
2002-10-23T21:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/OpenTypeSelectionDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; /** * A dialog to select a type from a list of types. The selected type will be * opened in the editor. */ public class OpenTypeSelectionDialog extends TypeSelectionDialog { public static final int IN_HIERARCHY= IDialogConstants.CLIENT_ID + 1; /** * Constructs an instance of <code>OpenTypeSelectionDialog</code>. * @param parent the parent shell. * @param context the context. * @param elementKinds <code>IJavaSearchConstants.CLASS</code>, <code>IJavaSearchConstants.INTERFACE</code> * or <code>IJavaSearchConstants.TYPE</code> * @param scope the java search scope. */ public OpenTypeSelectionDialog(Shell parent, IRunnableContext context, int elementKinds, IJavaSearchScope scope) { super(parent, context, elementKinds, scope); } /** * @see Windows#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.OPEN_TYPE_DIALOG); } }
26,453
Bug 26453 Use of extracted constant should be qualified by class name
When extracting a constant the constant should be qualified by the enclosing class name since its static. e.g. return "foo"; replaced by return Enclosing.FOO_CONSTANTS
resolved fixed
d3b545a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T16:58:09Z
2002-11-15T11:33:20Z
org.eclipse.jdt.ui/core
26,453
Bug 26453 Use of extracted constant should be qualified by class name
When extracting a constant the constant should be qualified by the enclosing class name since its static. e.g. return "foo"; replaced by return Enclosing.FOO_CONSTANTS
resolved fixed
d3b545a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T16:58:09Z
2002-11-15T11:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java
26,453
Bug 26453 Use of extracted constant should be qualified by class name
When extracting a constant the constant should be qualified by the enclosing class name since its static. e.g. return "foo"; replaced by return Enclosing.FOO_CONSTANTS
resolved fixed
d3b545a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T16:58:09Z
2002-11-15T11:33:20Z
org.eclipse.jdt.ui/ui
26,453
Bug 26453 Use of extracted constant should be qualified by class name
When extracting a constant the constant should be qualified by the enclosing class name since its static. e.g. return "foo"; replaced by return Enclosing.FOO_CONSTANTS
resolved fixed
d3b545a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T16:58:09Z
2002-11-15T11:33:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ExtractConstantInputPage.java
24,674
Bug 24674 "try" template should use printStackTrace()
By default the "try" template is defined as: try { ${cursor} } catch (${Exception} e) { } It should probably use printStackTrace(), for example: try { ${cursor} } catch (${Exception} e) { e.printStackTrace(); } When you are not sure how to handle an exception, sending printStackTrace() is a useful best practice. Failing to do this causes thrown exception to be masked.
resolved fixed
67e7ee7
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T17:07:09Z
2002-10-10T20:00:00Z
org.eclipse.jdt.ui/core
24,674
Bug 24674 "try" template should use printStackTrace()
By default the "try" template is defined as: try { ${cursor} } catch (${Exception} e) { } It should probably use printStackTrace(), for example: try { ${cursor} } catch (${Exception} e) { e.printStackTrace(); } When you are not sure how to handle an exception, sending printStackTrace() is a useful best practice. Failing to do this causes thrown exception to be masked.
resolved fixed
67e7ee7
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T17:07:09Z
2002-10-10T20:00:00Z
extension/org/eclipse/jdt/internal/corext/template/java/JavaContextType.java
26,495
Bug 26495 inline constant inlines too many occurences
public class A { static final String D= B.G; void f(){ String s= B.G; } } class B{ static final String G= "FRED"; }
resolved fixed
db07fc1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T20:02:55Z
2002-11-15T17:06:40Z
org.eclipse.jdt.ui/ui
26,495
Bug 26495 inline constant inlines too many occurences
public class A { static final String D= B.G; void f(){ String s= B.G; } } class B{ static final String G= "FRED"; }
resolved fixed
db07fc1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-15T20:02:55Z
2002-11-15T17:06:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/InlineConstantInputPage.java
25,014
Bug 25014 JUnit TestCase Wizard accepts empty string as test case name[junit]
Version: 2.0 Build id: 200210161553 The JUnit TestCase wizard accepts empty string as the test case name when there is no Java class currently selected. Steps for reproducing the error: 1 - Ensure there is no class currently selected in the Package Explorer (e.g. select a package or project); 2 - Activate New JUnit TestCase wizard; 3 - There will be no test case name selected. The "Finish" button will be disabled. Then erase the "Superclass" field content. The "Finish" button will be enabled. This opens a dialog with a message "Creation of element failed. Reason: Invalid name specified: .java" and a new entry is added to the error log. The stack trace will be attached.
resolved fixed
d07b140
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-16T20:02:02Z
2002-10-17T18:40:00Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestCaseCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.wizards; import java.util.ArrayList; import java.util.HashMap; import java.util.ListIterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.JUnitStatus; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; import org.eclipse.jdt.internal.junit.util.LayoutUtil; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.ui.IJavaElementSearchConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; /** * The first page of the TestCase creation wizard. */ public class NewTestCaseCreationWizardPage extends NewTypeWizardPage { protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$ protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$ protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$ protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$ protected final static String SETUP= "setUp"; //$NON-NLS-1$ protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$ protected final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$ protected final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$ protected final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; //$NON-NLS-1$ private String fDefaultClassToTest; private NewTestCaseCreationWizardPage2 fPage2; private MethodStubsSelectionButtonGroup fMethodStubsButtons; private IType fClassToTest; protected IStatus fClassToTestStatus; protected IStatus fTestClassStatus; private int fIndexOfFirstTestMethod; private Label fClassToTestLabel; private Text fClassToTestText; private Button fClassToTestButton; private Label fTestClassLabel; private Text fTestClassText; private String fTestClassTextInitialValue; private IMethod[] fTestMethods; private IType fCreatedType; private boolean fFirstTime; public NewTestCaseCreationWizardPage() { super(true, PAGE_NAME); fFirstTime= true; fTestClassTextInitialValue= ""; //$NON-NLS-1$ setTitle(WizardMessages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$ setDescription(WizardMessages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$ String[] buttonNames= new String[] { "public static void main(Strin&g[] args)", //$NON-NLS-1$ /* Add testrunner statement to main Method */ WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$ WizardMessages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$ WizardMessages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$ }; fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1); fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$ fClassToTestStatus= new JUnitStatus(); fTestClassStatus= new JUnitStatus(); fDefaultClassToTest= ""; //$NON-NLS-1$ } // -------- Initialization --------- /** * Should be called from the wizard with the initial selection and the 2nd page of the wizard.. */ public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { fPage2= page2; IJavaElement element= getInitialJavaElement(selection); initContainerPage(element); initTypePage(element); doStatusUpdate(); // put default class to test if (element != null) { IType classToTest= null; // evaluate the enclosing type IType typeInCompUnit= (IType) element.getAncestor(IJavaElement.TYPE); if (typeInCompUnit != null) { if (typeInCompUnit.getCompilationUnit() != null) { classToTest= typeInCompUnit; } } else { ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) classToTest= cu.findPrimaryType(); else { if (element instanceof IClassFile) { try { IClassFile cf= (IClassFile) element; if (cf.isStructureKnown()) classToTest= cf.getType(); } catch(JavaModelException e) { JUnitPlugin.log(e); } } } } if (classToTest != null) { try { if (!TestSearchEngine.isTestImplementor(classToTest)) { fDefaultClassToTest= classToTest.getFullyQualifiedName(); } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } fMethodStubsButtons.setSelection(0, false); //main fMethodStubsButtons.setSelection(1, false); //add textrunner fMethodStubsButtons.setEnabled(1, false); //add text fMethodStubsButtons.setSelection(2, false); //setUp fMethodStubsButtons.setSelection(3, false); //tearDown } /** * @see NewContainerWizardPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName.equals(CLASS_TO_TEST)) { fClassToTestStatus= classToTestClassChanged(); updateDefaultName(); } else if (fieldName.equals(SUPER)) { validateSuperClass(); } else if (fieldName.equals(TEST_CLASS)) { fTestClassStatus= testClassChanged(); } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) { if (fieldName.equals(PACKAGE)) fPackageStatus= packageChanged(); if (!fFirstTime) { validateSuperClass(); fClassToTestStatus= classToTestClassChanged(); fTestClassStatus= testClassChanged(); } if (fieldName.equals(CONTAINER)) { validateJUnitOnBuildPath(); } } doStatusUpdate(); } // ------ validation -------- private void doStatusUpdate() { // status of all used components IStatus[] status= new IStatus[] { fContainerStatus, fPackageStatus, fTestClassStatus, fClassToTestStatus, fModifierStatus, fSuperClassStatus }; // the mode severe status will be displayed and the ok button enabled/disabled. updateStatus(status); } protected void updateDefaultName() { String s= fClassToTestText.getText(); if (s.lastIndexOf('.') > -1) s= s.substring(s.lastIndexOf('.') + 1); if (s.length() > 0) setTypeName(s + TEST_SUFFIX, true); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTestClassControls(composite, nColumns); createClassToTestControls(composite, nColumns); createSuperClassControls(composite, nColumns); createMethodStubSelectionControls(composite, nColumns); setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); setControl(composite); //set default and focus fClassToTestText.setText(fDefaultClassToTest); restoreWidgetValues(); WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE); } protected void createMethodStubSelectionControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); LayoutUtil.createEmptySpace(composite,1); LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); } protected void createClassToTestControls(Composite composite, int nColumns) { fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fClassToTestLabel.setFont(composite.getFont()); fClassToTestLabel.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fClassToTestLabel.setLayoutData(gd); fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); fClassToTestText.setEnabled(true); fClassToTestText.setFont(composite.getFont()); fClassToTestText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(CLASS_TO_TEST); } }); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fClassToTestText.setLayoutData(gd); fClassToTestButton= new Button(composite, SWT.PUSH); fClassToTestButton.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$ fClassToTestButton.setEnabled(true); fClassToTestButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { classToTestButtonPressed(); } public void widgetSelected(SelectionEvent e) { classToTestButtonPressed(); } }); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= false; gd.horizontalSpan= 1; gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton); gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); fClassToTestButton.setLayoutData(gd); } private void classToTestButtonPressed() { IType type= chooseClassToTestType(); if (type != null) { fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); handleFieldChanged(CLASS_TO_TEST); } } private IType chooseClassToTestType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return null; IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); IType type= null; try { SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, null); dialog.setTitle(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$ dialog.setMessage(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$ dialog.open(); if (dialog.getReturnCode() != SelectionDialog.OK) return type; else { Object[] resultArray= dialog.getResult(); if (resultArray != null && resultArray.length > 0) type= (IType) resultArray[0]; } } catch (JavaModelException e) { JUnitPlugin.log(e); } return type; } protected IStatus classToTestClassChanged() { fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); return status; } /** * Returns the content of the class to test text field. */ public String getClassToTestText() { return fClassToTestText.getText(); } /** * Returns the class to be tested. */ public IType getClassToTest() { return fClassToTest; } /** * Sets the name of the class to test. */ public void setClassToTest(String name) { fClassToTestText.setText(name); } /** * @see NewTypeWizardPage#createTypeMembers */ protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException { fIndexOfFirstTestMethod= 0; createConstructor(type, imports); if (fMethodStubsButtons.isSelected(0)) createMain(type); if (fMethodStubsButtons.isSelected(2)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(3)) { createTearDown(type, imports); } if (isNextPageValid()) { createTestMethodStubs(type); } } protected void createConstructor(IType type, ImportsManager imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String constr= ""; //$NON-NLS-1$ IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod constrMethod= superTypes[i].getMethod(superTypes[i].getElementName(), new String[] {"Ljava.lang.String;"}); //$NON-NLS-1$ if (constrMethod.exists() && constrMethod.isConstructor()) { methodTemplate= constrMethod; break; } } } } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (methodTemplate != null) { GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; constr= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { constr += "public "+getTypeName()+"(String name) {\nsuper(name);\n}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(constr, null, true, null); fIndexOfFirstTestMethod++; } protected void createMain(IType type) throws JavaModelException { type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null); fIndexOfFirstTestMethod++; } protected void createSetUp(IType type, ImportsManager imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String setUp= ""; //$NON-NLS-1$ IMethod methodTemplate= null; if (type.exists()) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {}); if (testMethod.exists()) { methodTemplate= testMethod; break; } } } } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (methodTemplate != null) { GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); } else { if (settings.createComments) setUp= "/**\n * Sets up the fixture, for example, open a network connection.\n * This method is called before a test is executed.\n * @throws Exception\n */\n"; //$NON-NLS-1$ setUp+= "protected void "+SETUP+"() throws Exception {}\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ } type.createMethod(setUp, null, false, null); fIndexOfFirstTestMethod++; } protected void createTearDown(IType type, ImportsManager imports) throws JavaModelException { ITypeHierarchy typeHierarchy= null; IType[] superTypes= null; String tearDown= ""; //$NON-NLS-1$ IMethod methodTemplate= null; if (type.exists()) { if (typeHierarchy == null) { typeHierarchy= type.newSupertypeHierarchy(null); superTypes= typeHierarchy.getAllSuperclasses(type); } for (int i= 0; i < superTypes.length; i++) { if (superTypes[i].exists()) { IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {}); if (testM.exists()) { methodTemplate= testM; break; } } } } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (methodTemplate != null) { GenStubSettings genStubSettings= new GenStubSettings(settings); genStubSettings.fCallSuper= true; genStubSettings.fMethodOverwrites= true; tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); type.createMethod(tearDown, null, false, null); fIndexOfFirstTestMethod++; } } protected void createTestMethodStubs(IType type) throws JavaModelException { IMethod[] methods= fPage2.getCheckedMethods(); if (methods.length > 0) { /* find overloaded methods */ ArrayList allMethods= new ArrayList(); IMethod[] allMethodsArray= fPage2.getAllMethods(); for (int i= 0; i < allMethodsArray.length; i++) { allMethods.add(allMethodsArray[i]); } ArrayList overloadedMethods= new ArrayList(); for (int i= 0; i < allMethods.size(); i++) { IMethod current= (IMethod) allMethods.get(i); String currentName= current.getElementName(); boolean currentAdded= false; for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { IMethod iterMethod= (IMethod) iter.next(); if (iterMethod.getElementName().equals(currentName)) { //method is overloaded if (!currentAdded) { overloadedMethods.add(current); currentAdded= true; } overloadedMethods.add(iterMethod); iter.remove(); } } } /* used when for example both sum and Sum methods are present. Then * sum -> testSum * Sum -> testSum1 */ ArrayList newMethodsNames= new ArrayList(); for (int i = 0; i < methods.length; i++) { String elementName= methods[i].getElementName(); StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); StringBuffer newMethod= new StringBuffer(); if (overloadedMethods.contains(methods[i])) { IMethod method= methods[i]; String returnType= Signature.toString(method.getReturnType()); String body= WizardMessages.getFormattedString("NewTestClassWizPage.comment.class_to_test", new String[]{returnType, method.getElementName()}); //$NON-NLS-1$ newMethod.append("/*\n * "+body+"("); //$NON-NLS-1$ //$NON-NLS-2$ String[] paramTypes= method.getParameterTypes(); if (paramTypes.length > 0) { if (paramTypes.length > 1) { for (int j= 0; j < paramTypes.length-1; j++) { newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$ } } newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); } newMethod.append(")\n */\n"); //$NON-NLS-1$ String[] params= methods[i].getParameterTypes(); for (int j= 0; j < params.length; j++) { String param= params[j]; int start= 0, end= param.length(); //using JDK 1.4: // (new Character(Signature.C_ARRAY)).toString() --> Character.toString(Signature.C_ARRAY) if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) start= 1; if (param.endsWith((new Character(Signature.C_NAME_END)).toString() )) end--; if (param.startsWith((new Character(Signature.C_UNRESOLVED)).toString() ,start) || param.startsWith((new Character(Signature.C_RESOLVED)).toString() ,start)) start++; String paramName= param.substring(start, end); /* if parameter is qualified name, extract simple name */ if (paramName.indexOf('.') != -1) { start += paramName.lastIndexOf('.')+1; } methodName.append(param.substring(start, end)); if (param.startsWith( (new Character(Signature.C_ARRAY)).toString() )) methodName.append("Array"); //$NON-NLS-1$ } } /* Should I for examples have methods * void foo(java.lang.StringBuffer sb) {} * void foo(mypackage1.StringBuffer sb) {} * void foo(mypackage2.StringBuffer sb) {} * I will get in the test class: * testFooStringBuffer() * testFooStringBuffer1() * testFooStringBuffer2() */ if (newMethodsNames.contains(methodName.toString())) { int suffix= 1; while (newMethodsNames.contains(methodName.toString() + Integer.toString(suffix))) suffix++; methodName.append(Integer.toString(suffix)); } newMethodsNames.add(new String(methodName)); newMethod.append("public void "+methodName.toString()+"() {}\n\n"); //$NON-NLS-1$ //$NON-NLS-2$ type.createMethod(newMethod.toString(), null, false, null); } } } /** * @see DialogPage#setVisible(boolean) */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible && fFirstTime) { handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists if (getClassToTestText().equals("")) //$NON-NLS-1$ setPageComplete(false); fFirstTime= false; } if (visible) setFocus(); } private void validateJUnitOnBuildPath() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) return; IJavaProject jp= root.getJavaProject(); try { if (jp.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) != null) return; } catch (JavaModelException e) { } JUnitStatus status= new JUnitStatus(); status.setError(WizardMessages.getString("NewTestClassWizPage.error.junitNotOnbuildpath")); //$NON-NLS-1$ fContainerStatus= status; } /** * Returns the index of the first method that is a test method, i.e. excluding main, setUp() and tearDown(). * If none of the aforementioned method stubs is created, then 0 is returned. As such method stubs are created, * this counter is incremented. */ public int getIndexOfFirstMethod() { return fIndexOfFirstTestMethod; } /** * @see IDialogPage#createControl(Composite) */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); if (fPage2.getCreateTasksButtonSelection()) { createTaskMarkers(); } } private void createTaskMarkers() throws CoreException { IType createdType= getCreatedType(); fTestMethods= createdType.getMethods(); ICompilationUnit cu= createdType.getCompilationUnit(); cu.save(null, false); IResource res= createdType.getCompilationUnit().getResource(); if (res == null) return; for (int i= getIndexOfFirstMethod(); i < fTestMethods.length; i++) { IMethod method= fTestMethods[i]; IMarker marker= res.createMarker("org.eclipse.jdt.junit.junit_task"); //$NON-NLS-1$ HashMap attributes= new HashMap(10); attributes.put(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); attributes.put(IMarker.MESSAGE, WizardMessages.getFormattedString("NewTestClassWizPage.marker.message",method.getElementName())); //$NON-NLS-1$ ISourceRange markerRange= method.getSourceRange(); attributes.put(IMarker.CHAR_START, new Integer(markerRange.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(markerRange.getOffset()+markerRange.getLength())); marker.setAttributes(attributes); } } private void validateSuperClass() { fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox String superClassName= getSuperClass(); if (superClassName != null && !superClassName.equals("") && getPackageFragmentRoot() != null) { //$NON-NLS-1$ try { IType type= resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); JUnitStatus status = new JUnitStatus(); if (type == null) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$ fSuperClassStatus= status; } else { if (type.isInterface()) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$ fSuperClassStatus= status; } if (!TestSearchEngine.isTestImplementor(type)) { status.setError(WizardMessages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$ fSuperClassStatus= status; } else { IMethod setupMethod= type.getMethod(SETUP, new String[] {}); IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {}); if (setupMethod.exists()) fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); if (teardownMethod.exists()) fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); } } } catch (JavaModelException e) { JUnitPlugin.log(e); } } } protected void createTestClassControls(Composite composite, int nColumns) { fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP); fTestClassLabel.setFont(composite.getFont()); fTestClassLabel.setText(WizardMessages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fTestClassLabel.setLayoutData(gd); fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER); fTestClassText.setEnabled(true); fTestClassText.setFont(composite.getFont()); fTestClassText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleFieldChanged(TEST_CLASS); } }); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= true; gd.horizontalSpan= nColumns - 2; fTestClassText.setLayoutData(gd); Label space= new Label(composite, SWT.LEFT); space.setText(" "); //$NON-NLS-1$ gd= new GridData(); gd.horizontalSpan= 1; space.setLayoutData(gd); } /** * Gets the type name. */ public String getTypeName() { return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText(); } /** * Sets the type name. */ public void setTypeName(String name, boolean canBeModified) { if (fTestClassText == null) { fTestClassTextInitialValue= name; } else { fTestClassText.setText(name); fTestClassText.setEnabled(canBeModified); } } /** * Called when the type name has changed. * The method validates the type name and returns the status of the validation. * Can be extended to add more validation */ protected IStatus testClassChanged() { JUnitStatus status= new JUnitStatus(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$ // continue checking } IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.already_exists")); //$NON-NLS-1$ return status; } } return status; } /** * @see IWizardPage#canFlipToNextPage */ public boolean canFlipToNextPage() { return isPageComplete() && getNextPage() != null && isNextPageValid(); } protected boolean isNextPageValid() { return !getClassToTestText().equals(""); //$NON-NLS-1$ } protected JUnitStatus validateClassToTest() { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); String classToTestName= fClassToTestText.getText(); JUnitStatus status= new JUnitStatus(); fClassToTest= null; if (classToTestName.length() == 0) { return status; } IStatus val= JavaConventions.validateJavaTypeName(classToTestName); // if (!val.isOK()) { if (val.getSeverity() == IStatus.ERROR) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName); //IType type= wizpage.resolveClassToTestName(); if (type == null) { //status.setWarning("Warning: "+typeLabel+" does not exist in current project."); status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$ } if (pack != null && !JavaModelUtil.isVisible(type, pack)) { status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String[] {(type.isInterface())?WizardMessages.getString("Interface"):WizardMessages.getString("Class") , classToTestName})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } fClassToTest= type; } catch (JavaModelException e) { status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$ } } else { status.setError(""); //$NON-NLS-1$ } return status; } static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { IType type= null; if (type == null && pack != null) { String packName= pack.getElementName(); // search in own package if (!pack.isDefaultPackage()) { type= jproject.findType(packName, classToTestName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= jproject.findType("java.lang", classToTestName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= jproject.findType(classToTestName); } return type; } /** * Sets the focus on the type name. */ protected void setFocus() { fTestClassText.setFocus(); fTestClassText.setSelection(fTestClassText.getText().length(), fTestClassText.getText().length()); } /** * Use the dialog store to restore widget values to the values that they held * last time this wizard was used to completion */ private void restoreWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN); fMethodStubsButtons.setSelection(0, generateMain); fMethodStubsButtons.setEnabled(1, generateMain); fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER)); try { fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE)); } catch(NumberFormatException e) {} } } /** * Since Finish was pressed, write widget values to the dialog store so that they * will persist into the next invocation of this wizard page */ void saveWidgetValues() { IDialogSettings settings= getDialogSettings(); if (settings != null) { settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0)); settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1)); settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection()); } } }
26,380
Bug 26380 GUI bloopers: Navigate > Go To > Referring Tests
null
resolved fixed
d825124
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-16T22:09:27Z
2002-11-14T18:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestMethodSelectionDialog.java
package org.eclipse.jdt.internal.junit.ui; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.lang.reflect.InvocationTargetException; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchResultCollector; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; /** * A dialog to select a test method. */ public class TestMethodSelectionDialog extends ElementListSelectionDialog { private IRunnableContext fRunnableContext; private IJavaElement fElement; public static class TestReferenceCollector implements IJavaSearchResultCollector { IProgressMonitor fMonitor; Set fResult= new HashSet(200); public TestReferenceCollector(IProgressMonitor pm) { fMonitor= pm; } public void aboutToStart() { } public void accept(IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy) throws CoreException { if (enclosingElement.getElementName().startsWith("test")) fResult.add(enclosingElement); } public void done() { } public IProgressMonitor getProgressMonitor() { return fMonitor; } public Object[] getResult() { return fResult.toArray(); } } public TestMethodSelectionDialog(Shell shell, IRunnableContext context, IJavaElement element) { super(shell, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_PARAMETERS | JavaElementLabelProvider.SHOW_POST_QUALIFIED)); fRunnableContext= context; fElement= element; } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJUnitHelpContextIds.TEST_SELECTION_DIALOG); } /* * @see Window#open() */ public int open() { Object[] elements; IType testType= findTestType(); if (testType == null) return CANCEL; try { elements= searchTestMethods(fElement, testType, fRunnableContext); } catch (InterruptedException e) { return CANCEL; } catch (InvocationTargetException e) { MessageDialog.openError(getShell(), "Select Test", e.getTargetException().getMessage()); return CANCEL; } if (elements.length == 0) { MessageDialog.openInformation(getShell(), "Go to Test", "No Tests Found that reference '"+fElement.getElementName()+"'."); return CANCEL; } setElements(elements); return super.open(); } private IType findTestType() { String qualifiedName= JUnitPlugin.TEST_INTERFACE_NAME; IJavaProject[] projects; Set result= new HashSet(); try { projects= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects(); for (int i= 0; i < projects.length; i++) { IJavaProject project= projects[i]; IType type= project.findType(qualifiedName); if (type != null) result.add(type); } } catch (JavaModelException e) { ErrorDialog.openError(getShell(), "Find Test", "Could not find test", e.getStatus()); return null; } if (result.size() == 0) { MessageDialog.openError(getShell(), "Select Test", "Cannot find '"+JUnitPlugin.TEST_INTERFACE_NAME+"' - make sure that JUnit is on the project's classpath."); return null; } if (result.size() == 1) return (IType)result.toArray()[0]; return selectTestType(result); } private IType selectTestType(Set result) { ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_PARAMETERS | JavaElementLabelProvider.SHOW_ROOT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(null, labelProvider); dialog.setTitle("Go To Referring Tests"); dialog.setMessage("More than project contains the type junit.framework.Test. Select the type you want to find referring tests."); dialog.setElements(result.toArray()); if (dialog.open() == ElementListSelectionDialog.CANCEL) return null; return (IType) dialog.getFirstResult(); } public Object[] searchTestMethods(final IJavaElement element, final IType testType, IRunnableContext context) throws InvocationTargetException, InterruptedException { final TestReferenceCollector[] col= new TestReferenceCollector[1]; IRunnableWithProgress runnable= new IRunnableWithProgress() { public void run(IProgressMonitor pm) throws InvocationTargetException { try { col[0]= doSearchTestMethods(element, testType, pm); } catch (JavaModelException e) { throw new InvocationTargetException(e); } } }; context.run(true, true, runnable); return col[0].getResult(); } private TestReferenceCollector doSearchTestMethods(IJavaElement element, IType testType, IProgressMonitor pm) throws JavaModelException{ IJavaSearchScope scope= SearchEngine.createHierarchyScope(testType); TestReferenceCollector collector= new TestReferenceCollector(pm); new SearchEngine().search(ResourcesPlugin.getWorkspace(), element, IJavaSearchConstants.REFERENCES, scope, collector); return collector; } }
26,257
Bug 26257 JUnit: New Test Case wizard generates code which does not compile
Build 20021113 This might be intentional: when I choose to generate the main class then the generate code contains a compile error: public static void main(String[] args) { junit.textui.TestRunner.run(TestCaseTest.suite()); } TestCaseTest.suite() does not exist.
resolved fixed
8edde36
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-16T23:37:43Z
2002-11-14T10:33:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/MethodStubsSelectionButtonGroup.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.junit.wizards; import org.eclipse.jdt.internal.junit.util.*; import org.eclipse.jface.util.Assert; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; /** * A group of controls used in the JUnit TestCase and TestSuite wizards * for selecting method stubs to create. */ public class MethodStubsSelectionButtonGroup { private Label fLabel; protected String fLabelText; private SelectionButtonGroupListener fGroupListener; private boolean fEnabled; private Composite fButtonComposite; private Button[] fButtons; private String[] fButtonNames; private boolean[] fButtonsSelected; private boolean[] fButtonsEnabled; private Combo fMainCombo; private boolean fMainComboEnabled; private int fGroupBorderStyle; private int fGroupNumberOfColumns; private int fButtonsStyle; public interface SelectionButtonGroupListener { /** * The dialog field has changed. */ void groupChanged(MethodStubsSelectionButtonGroup field); } /** * Creates a group without border. */ public MethodStubsSelectionButtonGroup(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 MethodStubsSelectionButtonGroup(int buttonsStyle, String[] buttonNames, int nColumns, int borderStyle) { fEnabled= true; fLabel= null; fLabelText= ""; //$NON-NLS-1$ Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE); fButtonNames= buttonNames; int nButtons= buttonNames.length; fButtonsSelected= new boolean[nButtons]; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsSelected[i]= false; fButtonsEnabled[i]= true; } fMainComboEnabled= true; if (fButtonsStyle == SWT.RADIO) { fButtonsSelected[0]= true; } fGroupBorderStyle= borderStyle; fGroupNumberOfColumns= (nColumns <= 0) ? nButtons : nColumns; fButtonsStyle= buttonsStyle; } /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); if (fGroupBorderStyle == SWT.NONE) { Label label= getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); Composite buttonsgroup= getSelectionButtonsGroup(parent); GridData gd= new GridData(); gd.horizontalSpan= nColumns - 1; buttonsgroup.setLayoutData(gd); return new Control[] { label, buttonsgroup }; } else { Composite buttonsgroup= getSelectionButtonsGroup(parent); GridData gd= new GridData(); gd.horizontalSpan= nColumns; buttonsgroup.setLayoutData(gd); return new Control[] { buttonsgroup }; } } /* * @see DialogField#doFillIntoGrid */ public int getNumberOfControls() { return (fGroupBorderStyle == SWT.NONE) ? 2 : 1; } private Button createSelectionButton(int index, Composite group, SelectionListener listener) { Button button= new Button(group, fButtonsStyle | SWT.LEFT); button.setFont(group.getFont()); button.setText(fButtonNames[index]); button.setEnabled(isEnabled() && fButtonsEnabled[index]); button.setSelection(fButtonsSelected[index]); button.addSelectionListener(listener); button.setLayoutData(new GridData()); return button; } private Button createMainCombo(int index, Composite group, SelectionListener listener) { Composite buttonComboGroup= new Composite(group, 0); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 20; layout.numColumns= 2; buttonComboGroup.setLayout(layout); Button button= new Button(buttonComboGroup, fButtonsStyle | SWT.LEFT); button.setFont(group.getFont()); button.setText(fButtonNames[index]); button.setEnabled(isEnabled() && fButtonsEnabled[index]); button.setSelection(fButtonsSelected[index]); button.addSelectionListener(listener); button.setLayoutData(new GridData()); fMainCombo= new Combo(buttonComboGroup, SWT.READ_ONLY); fMainCombo.setItems(new String[] {"text ui","swing ui","awt ui"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ fMainCombo.select(0); fMainCombo.setEnabled(isEnabled() && fMainComboEnabled); fMainCombo.setFont(group.getFont()); fMainCombo.setLayoutData(new GridData()); return button; } public String getMainMethod(String typeName) { StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$ if (isSelected(1)) { main.append("junit."); //$NON-NLS-1$ switch (getComboSelection()) { case 0: main.append("textui"); //$NON-NLS-1$ break; case 1: main.append("swingui"); //$NON-NLS-1$ break; case 2 : main.append("awtui"); //$NON-NLS-1$ break; default : main.append("textui"); //$NON-NLS-1$ break; } main.append(".TestRunner.run(" + typeName + ".suite());"); //$NON-NLS-1$ //$NON-NLS-2$ } main.append("}\n\n"); //$NON-NLS-1$ return main.toString(); } /** * Returns the group widget. When called the first time, the widget will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getSelectionButtonsGroup(Composite parent) { if (fButtonComposite == null) { assertCompositeNotNull(parent); GridLayout layout= new GridLayout(); layout.makeColumnsEqualWidth= true; layout.numColumns= fGroupNumberOfColumns; if (fGroupBorderStyle != SWT.NONE) { Group group= new Group(parent, fGroupBorderStyle); if (fLabelText != null && fLabelText.length() > 0) { group.setText(fLabelText); } fButtonComposite= group; } else { fButtonComposite= new Composite(parent, SWT.NULL); layout.marginHeight= 0; layout.marginWidth= 0; } fButtonComposite.setLayout(layout); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doWidgetSelected(e); } public void widgetSelected(SelectionEvent e) { doWidgetSelected(e); } }; int nButtons= fButtonNames.length; fButtons= new Button[nButtons]; fButtons[0]= createSelectionButton(0, fButtonComposite, listener); fButtons[1]= createMainCombo(1, fButtonComposite, listener); for (int i= 2; i < nButtons; i++) { fButtons[i]= createSelectionButton(i, fButtonComposite, listener); } int nRows= nButtons / fGroupNumberOfColumns; int nFillElements= nRows * fGroupNumberOfColumns - nButtons; for (int i= 0; i < nFillElements; i++) { createEmptySpace(fButtonComposite); } setSelectionGroupListener(new SelectionButtonGroupListener() { public void groupChanged(MethodStubsSelectionButtonGroup field) { field.setEnabled(1, isEnabled() && field.isSelected(0)); } }); } return fButtonComposite; } /** * Returns a button from the group or <code>null</code> if not yet created. */ public Button getSelectionButton(int index) { if (index >= 0 && index < fButtons.length) { return fButtons[index]; } return null; } private void doWidgetSelected(SelectionEvent e) { Button button= (Button)e.widget; for (int i= 0; i < fButtons.length; i++) { if (fButtons[i] == button) { fButtonsSelected[i]= button.getSelection(); dialogFieldChanged(); return; } } } /** * Returns the selection state of a button contained in the group. * @param The index of the button */ public boolean isSelected(int index) { if (index >= 0 && index < fButtonsSelected.length) { return fButtonsSelected[index]; } return false; } /** * Sets the selection state of a button contained in the group. */ public void setSelection(int index, boolean selected) { if (index >= 0 && index < fButtonsSelected.length) { if (fButtonsSelected[index] != selected) { fButtonsSelected[index]= selected; if (fButtons != null) { Button button= fButtons[index]; if (isOkToUse(button)) { button.setSelection(selected); } } } } } /** * Returns the enabled state of a button contained in the group. * @param The index of the button */ public boolean isEnabled(int index) { if (index >= 0 && index < fButtonsEnabled.length) { return fButtonsEnabled[index]; } return false; } /** * Sets the selection state of a button contained in the group. */ public void setEnabled(int index, boolean enabled) { if (index >= 0 && index < fButtonsEnabled.length) { if (fButtonsEnabled[index] != enabled) { fButtonsEnabled[index]= enabled; if (index == 1) fMainComboEnabled= enabled; if (fButtons != null) { Button button= fButtons[index]; if (isOkToUse(button)) { button.setEnabled(enabled); if (index == 1) fMainCombo.setEnabled(isEnabled() && enabled); } } } } } protected void updateEnableState() { if (fLabel != null) { fLabel.setEnabled(fEnabled); } if (fButtons != null) { boolean enabled= isEnabled(); for (int i= 0; i < fButtons.length; i++) { Button button= fButtons[i]; if (isOkToUse(button)) { button.setEnabled(enabled && fButtonsEnabled[i]); } } fMainCombo.setEnabled(enabled && fMainComboEnabled); } } public int getComboSelection() { return fMainCombo.getSelectionIndex(); } public void setComboSelection(int index) { fMainCombo.select(index); } /** * Sets the label of the dialog field. */ public void setLabelText(String labeltext) { fLabelText= labeltext; } /** * Defines the listener for this dialog field. */ public final void setSelectionGroupListener(SelectionButtonGroupListener listener) { fGroupListener= listener; } /** * Programatical invocation of a dialog field change. */ public void dialogFieldChanged() { if (fGroupListener != null) { fGroupListener.groupChanged(this); } } /** * Tries to set the focus to the dialog field. * Returns <code>true</code> if the dialog field can take focus. * To be reimplemented by dialog field implementors. */ public boolean setFocus() { return false; } /** * Posts <code>setFocus</code> to the display event queue. */ public void postSetFocusOnDialogField(Display display) { if (display != null) { display.asyncExec( new Runnable() { public void run() { setFocus(); } } ); } } protected static GridData gridDataForLabel(int span) { GridData gd= new GridData(); gd.horizontalSpan= span; return gd; } /** * Creates or returns the created label widget. * @param parent The parent composite or <code>null</code> if the widget has * already been created. */ public Label getLabelControl(Composite parent) { if (fLabel == null) { assertCompositeNotNull(parent); fLabel= new Label(parent, SWT.LEFT | SWT.WRAP); fLabel.setFont(parent.getFont()); fLabel.setEnabled(fEnabled); if (fLabelText != null && !"".equals(fLabelText)) { //$NON-NLS-1$ fLabel.setText(fLabelText); } else { // XXX: to avoid a 16 pixel wide empty label - revisit fLabel.setText("."); //$NON-NLS-1$ fLabel.setVisible(false); } } return fLabel; } /** * Creates a spacer control. * @param parent The parent composite */ public static Control createEmptySpace(Composite parent) { return createEmptySpace(parent, 1); } /** * Creates a spacer control with the given span. * The composite is assumed to have <code>MGridLayout</code> as * layout. * @param parent The parent composite */ public static Control createEmptySpace(Composite parent, int span) { return LayoutUtil.createEmptySpace(parent, span); } /** * Tests is the control is not <code>null</code> and not disposed. */ protected final boolean isOkToUse(Control control) { return (control != null) && !(control.isDisposed()); } // --------- enable / disable management /** * Sets the enable state of the dialog field. */ public final void setEnabled(boolean enabled) { if (enabled != fEnabled) { fEnabled= enabled; updateEnableState(); } } /** * Gets the enable state of the dialog field. */ public final boolean isEnabled() { return fEnabled; } protected final void assertCompositeNotNull(Composite comp) { Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$ } protected final void assertEnoughColumns(int nColumns) { Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$ } }
26,231
Bug 26231 Editor on method must be opened in order to delete it from the Members context menu. [refactoring]
Select a method in the Members pane on a class that is /not/ being edited. Open the context menu and the "Delete" operation is disabled. Workaround: Double click the method which opens it in an editor, /then/ you can open the context menu and choose "Delete". IMHO, I should not be forced to perform this extra step. Build id: 200211051258
resolved fixed
e81a481
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T14:14:08Z
2002-11-14T02:13:20Z
org.eclipse.jdt.ui/core
26,231
Bug 26231 Editor on method must be opened in order to delete it from the Members context menu. [refactoring]
Select a method in the Members pane on a class that is /not/ being edited. Open the context menu and the "Delete" operation is disabled. Workaround: Double click the method which opens it in an editor, /then/ you can open the context menu and choose "Delete". IMHO, I should not be forced to perform this extra step. Build id: 200211051258
resolved fixed
e81a481
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T14:14:08Z
2002-11-14T02:13:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/DeleteRefactoring.java
26,382
Bug 26382 Exception renaming source folder [refactoring]
Build 20021113 Linux-GTK In the packages view, I right clicked on a source folder and choose "Refactor->Rename" and renamed my plug-in's only source folder from "src-editorlist" to "src". A dialog popped up many times: Title: Reorganize Message: Unexpected exception. See log for details Reason: src-editorlist [in EditorList] does not exist Many exceptions were written to my log (471K worth), but they all top stack frames were the same. The following is the first trace that appears in the log: !SESSION Nov 14, 2002 12:40:29.521 --------------------------------------------- java.version=1.3.1_03 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86 -debug -dev bin -data /home/jburns/target -install file:/home/jburns/host/eclipse/ !ENTRY org.eclipse.jdt.ui 4 1 Nov 14, 2002 12:40:29.522 !MESSAGE Internal Error !STACK 1 Java Model Exception: Java Model Status [src-editorlist [in EditorList] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException(JavaElement.java:488) at org.eclipse.jdt.internal.core.PackageFragmentRoot.openWhenClosed(PackageFragmentRoot.java:368) at org.eclipse.jdt.internal.core.JavaElement.openHierarchy(JavaElement.java:509) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:296) at org.eclipse.jdt.internal.core.PackageFragmentRoot.getKind(PackageFragmentRoot.java:207) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring.isSourceFolder(ReorgRefactoring.java:627) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring.hasSourceFolders(ReorgRefactoring.java:315) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring.checkActivation(ReorgRefactoring.java:88) at org.eclipse.jdt.internal.ui.reorg.ClipboardActionUtil.canActivate(ClipboardActionUtil.java:125) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.canOperateOn(ReorgDestinationAction.java:74) at org.eclipse.jdt.internal.ui.reorg.JdtMoveAction.canOperateOn(JdtMoveAction.java:59) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.selectionChanged(ReorgDestinationAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged(SelectionDispatchAction.java:181) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.selectionChanged(SelectionDispatchAction.java:176) at org.eclipse.jdt.ui.actions.MoveAction.selectionChanged(MoveAction.java:76) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java:147) at org.eclipse.jface.viewers.StructuredViewer.updateSelection(StructuredViewer.java:1151) at org.eclipse.jface.viewers.StructuredViewer.handleSelect(StructuredViewer.java:540) at org.eclipse.jface.viewers.StructuredViewer$1.widgetSelected(StructuredViewer.java:564) at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent(OpenStrategy.java:172) at org.eclipse.jface.util.OpenStrategy.access$3(OpenStrategy.java:167) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:302) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:839) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1464) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1284) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1419) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1402) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
39c411b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T14:21:02Z
2002-11-14T18:53:20Z
org.eclipse.jdt.ui/core
26,382
Bug 26382 Exception renaming source folder [refactoring]
Build 20021113 Linux-GTK In the packages view, I right clicked on a source folder and choose "Refactor->Rename" and renamed my plug-in's only source folder from "src-editorlist" to "src". A dialog popped up many times: Title: Reorganize Message: Unexpected exception. See log for details Reason: src-editorlist [in EditorList] does not exist Many exceptions were written to my log (471K worth), but they all top stack frames were the same. The following is the first trace that appears in the log: !SESSION Nov 14, 2002 12:40:29.521 --------------------------------------------- java.version=1.3.1_03 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86 -debug -dev bin -data /home/jburns/target -install file:/home/jburns/host/eclipse/ !ENTRY org.eclipse.jdt.ui 4 1 Nov 14, 2002 12:40:29.522 !MESSAGE Internal Error !STACK 1 Java Model Exception: Java Model Status [src-editorlist [in EditorList] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException(JavaElement.java:488) at org.eclipse.jdt.internal.core.PackageFragmentRoot.openWhenClosed(PackageFragmentRoot.java:368) at org.eclipse.jdt.internal.core.JavaElement.openHierarchy(JavaElement.java:509) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:296) at org.eclipse.jdt.internal.core.PackageFragmentRoot.getKind(PackageFragmentRoot.java:207) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring.isSourceFolder(ReorgRefactoring.java:627) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring.hasSourceFolders(ReorgRefactoring.java:315) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring.checkActivation(ReorgRefactoring.java:88) at org.eclipse.jdt.internal.ui.reorg.ClipboardActionUtil.canActivate(ClipboardActionUtil.java:125) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.canOperateOn(ReorgDestinationAction.java:74) at org.eclipse.jdt.internal.ui.reorg.JdtMoveAction.canOperateOn(JdtMoveAction.java:59) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.selectionChanged(ReorgDestinationAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged(SelectionDispatchAction.java:181) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.selectionChanged(SelectionDispatchAction.java:176) at org.eclipse.jdt.ui.actions.MoveAction.selectionChanged(MoveAction.java:76) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java:147) at org.eclipse.jface.viewers.StructuredViewer.updateSelection(StructuredViewer.java:1151) at org.eclipse.jface.viewers.StructuredViewer.handleSelect(StructuredViewer.java:540) at org.eclipse.jface.viewers.StructuredViewer$1.widgetSelected(StructuredViewer.java:564) at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent(OpenStrategy.java:172) at org.eclipse.jface.util.OpenStrategy.access$3(OpenStrategy.java:167) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:302) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:839) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1464) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1284) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1419) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1402) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
resolved fixed
39c411b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T14:21:02Z
2002-11-14T18:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgRefactoring.java
26,451
Bug 26451 refactoring pref page: use groups for accessibility
20021114
resolved fixed
8040fa3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T14:30:22Z
2002-11-15T08:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/RefactoringPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.preference.FieldEditorPreferencePage; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.RadioGroupFieldEditor; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatus; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; public class RefactoringPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public static final String FATAL_SEVERITY= PreferenceConstants.REFACTOR_FATAL_SEVERITY; public static final String ERROR_SEVERITY= PreferenceConstants.REFACTOR_ERROR_SEVERITY; public static final String WARNING_SEVERITY= PreferenceConstants.REFACTOR_WARNING_SEVERITY; public static final String INFO_SEVERITY= PreferenceConstants.REFACTOR_INFO_SEVERITY; public static final String OK_SEVERITY= PreferenceConstants.REFACTOR_OK_SEVERITY; public static final String PREF_ERROR_PAGE_SEVERITY_THRESHOLD= PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD; public static final String PREF_SAVE_ALL_EDITORS= PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS; //public static final String PREF_JAVA_STYLE_GUIDE_CONFORM= "Refactoring.javaStyleGuideConform"; //$NON-NLS-1$ public RefactoringPreferencePage() { super(GRID); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); } /* public static void initDefaults(IPreferenceStore store) { store.setDefault(PREF_ERROR_PAGE_SEVERITY_THRESHOLD, ERROR_SEVERITY); //store.setDefault(PREF_JAVA_STYLE_GUIDE_CONFORM, true); store.setDefault(PREF_SAVE_ALL_EDITORS, false); } */ public void createControl(Composite parent) { // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.REFACTORING_PREFERENCE_PAGE); } public void createFieldEditors() { addField(createSeverityLevelField(getFieldEditorParent())); addField(createSaveAllField(getFieldEditorParent())); } private FieldEditor createSeverityLevelField(Composite parent){ RadioGroupFieldEditor editor= new RadioGroupFieldEditor( PREF_ERROR_PAGE_SEVERITY_THRESHOLD, RefactoringMessages.getString("RefactoringPreferencePage.show_error_page"), //$NON-NLS-1$ 1, new String[] [] { { RefactoringMessages.getString("RefactoringPreferencePage.fatal_error"), FATAL_SEVERITY }, //$NON-NLS-1$ { RefactoringMessages.getString("RefactoringPreferencePage.error"), ERROR_SEVERITY }, //$NON-NLS-1$ { RefactoringMessages.getString("RefactoringPreferencePage.warning"), WARNING_SEVERITY }, //$NON-NLS-1$ { RefactoringMessages.getString("RefactoringPreferencePage.info"), INFO_SEVERITY } //$NON-NLS-1$ }, parent ); return editor; } private FieldEditor createSaveAllField(Composite parent){ BooleanFieldEditor editor= new BooleanFieldEditor( PREF_SAVE_ALL_EDITORS, RefactoringMessages.getString("RefactoringPreferencePage.auto_save"), //$NON-NLS-1$ BooleanFieldEditor.DEFAULT, parent); return editor; } public void init(IWorkbench workbench) { } static public int getCheckPassedSeverity() { String value= JavaPlugin.getDefault().getPreferenceStore().getString(PREF_ERROR_PAGE_SEVERITY_THRESHOLD); int threshold= RefactoringStatus.ERROR; try { threshold= Integer.valueOf(value).intValue() - 1; } catch (NumberFormatException e) { } return threshold; } /* static public boolean getCodeIsJavaStyleGuideConform() { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); return store.getBoolean(PREF_JAVA_STYLE_GUIDE_CONFORM); } */ static public boolean getSaveAllEditors() { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); return store.getBoolean(PREF_SAVE_ALL_EDITORS); } static public void setSaveAllEditors(boolean value) { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PREF_SAVE_ALL_EDITORS, value); } public boolean performOk() { JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } }
26,357
Bug 26357 Change Method Signature: displays error message on input page when table cell edit mode is entered then exitted
When a table cell (in the editable table of parameters) enters the editing state (i.e. when a caret appears in the cell), and then exits the editing state, an error message is displayed near the top of the wizard page saying "No parameters were modified, reordered or added, the visibility and return type are unchanged." (A user can make a cell enter the editing state by double clicking on it, or selecting it immediately after some other cell was selected)
resolved fixed
58cbf14
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T15:45:20Z
2002-11-14T16:06:40Z
org.eclipse.jdt.ui/core
26,357
Bug 26357 Change Method Signature: displays error message on input page when table cell edit mode is entered then exitted
When a table cell (in the editable table of parameters) enters the editing state (i.e. when a caret appears in the cell), and then exits the editing state, an error message is displayed near the top of the wizard page saying "No parameters were modified, reordered or added, the visibility and return type are unchanged." (A user can make a cell enter the editing state by double clicking on it, or selecting it immediately after some other cell was selected)
resolved fixed
58cbf14
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T15:45:20Z
2002-11-14T16:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
26,357
Bug 26357 Change Method Signature: displays error message on input page when table cell edit mode is entered then exitted
When a table cell (in the editable table of parameters) enters the editing state (i.e. when a caret appears in the cell), and then exits the editing state, an error message is displayed near the top of the wizard page saying "No parameters were modified, reordered or added, the visibility and return type are unchanged." (A user can make a cell enter the editing state by double clicking on it, or selecting it immediately after some other cell was selected)
resolved fixed
58cbf14
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T15:45:20Z
2002-11-14T16:06:40Z
org.eclipse.jdt.ui/ui
26,357
Bug 26357 Change Method Signature: displays error message on input page when table cell edit mode is entered then exitted
When a table cell (in the editable table of parameters) enters the editing state (i.e. when a caret appears in the cell), and then exits the editing state, an error message is displayed near the top of the wizard page saying "No parameters were modified, reordered or added, the visibility and return type are unchanged." (A user can make a cell enter the editing state by double clicking on it, or selecting it immediately after some other cell was selected)
resolved fixed
58cbf14
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T15:45:20Z
2002-11-14T16:06:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeSignatureInputPage.java
26,599
Bug 26599 BadLocationException in JavaAutoIndentStrategy
I20021115: - Open the Java editor - select/copy a couple of lines with soem indentation - select all lines and delete them - paste them into the empty editor -> JavaAutoIndentStrategy.calcShiftBackReplace: BadLocationException
resolved fixed
5324298
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T18:42:29Z
2002-11-18T17:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Iterator; import java.util.NoSuchElementException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; /** * Auto indent strategy sensitive to brackets. */ public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy { public JavaAutoIndentStrategy() { } // evaluate the line with the opening bracket that matches the closing bracket on the given line protected int findMatchingOpenBracket(IDocument d, int line, int end, int closingBracketIncrease) throws BadLocationException { int start= d.getLineOffset(line); int brackcount= getBracketCount(d, start, end, false) - closingBracketIncrease; // sum up the brackets counts of each line (closing brackets count negative, // opening positive) until we find a line the brings the count to zero while (brackcount < 0) { line--; if (line < 0) { return -1; } start= d.getLineOffset(line); end= start + d.getLineLength(line) - 1; brackcount += getBracketCount(d, start, end, false); } return line; } private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException { int bracketcount= 0; while (start < end) { char curr= d.getChar(start); start++; switch (curr) { case '/' : if (start < end) { char next= d.getChar(start); if (next == '*') { // a comment starts, advance to the comment end start= getCommentEnd(d, start + 1, end); } else if (next == '/') { // '//'-comment: nothing to do anymore on this line start= end; } } break; case '*' : if (start < end) { char next= d.getChar(start); if (next == '/') { // we have been in a comment: forget what we read before bracketcount= 0; start++; } } break; case '{' : bracketcount++; ignoreCloseBrackets= false; break; case '}' : if (!ignoreCloseBrackets) { bracketcount--; } break; case '"' : case '\'' : start= getStringEnd(d, start, end, curr); break; default : } } return bracketcount; } // ----------- bracket counting ------------------------------------------------------ private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '*') { if (pos < end && d.getChar(pos) == '/') { return pos + 1; } } } return end; } protected String getIndentOfLine(IDocument d, int line) throws BadLocationException { if (line > -1) { int start= d.getLineOffset(line); int end= start + d.getLineLength(line) - 1; int whiteend= findEndOfWhiteSpace(d, start, end); return d.get(start, whiteend - start); } else { return ""; //$NON-NLS-1$ } } private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '\\') { // ignore escaped characters pos++; } else if (curr == ch) { return pos; } } return end; } protected void smartInsertAfterBracket(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); int start= d.getLineOffset(line); int whiteend= findEndOfWhiteSpace(d, start, c.offset); // shift only when line does not contain any text up to the closing bracket if (whiteend == c.offset) { // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1 && indLine != line) { // take the indent of the found line StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine)); // add the rest of the current line including the just added close bracket replaceText.append(d.get(whiteend, c.offset - whiteend)); replaceText.append(c.text); // modify document command c.length += c.offset - start; c.offset= start; c.text= replaceText.toString(); } } } catch (BadLocationException excp) { System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message1")); //$NON-NLS-1$ } } protected void smartIndentAfterNewLine(IDocument d, DocumentCommand c) { int docLength= d.getLength(); if (c.offset == -1 || docLength == 0) return; try { int p= (c.offset == docLength ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); StringBuffer buf= new StringBuffer(c.text); if (c.offset < docLength && d.getChar(c.offset) == '}') { int indLine= findMatchingOpenBracket(d, line, c.offset, 0); if (indLine == -1) { indLine= line; } buf.append(getIndentOfLine(d, indLine)); } else { int start= d.getLineOffset(line); // if line just ended a javadoc comment, take the indent from the comment's begin line IDocumentPartitioner partitioner= d.getDocumentPartitioner(); if (partitioner != null) { ITypedRegion region= partitioner.getPartition(start); if (JavaPartitionScanner.JAVA_DOC.equals(region.getType())) start= d.getLineInformationOfOffset(region.getOffset()).getOffset(); } int whiteend= findEndOfWhiteSpace(d, start, c.offset); buf.append(d.get(start, whiteend - start)); if (getBracketCount(d, start, c.offset, true) > 0) { buf.append(getOneIndentLevel()); } } c.text= buf.toString(); } catch (BadLocationException excp) { System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message2")); //$NON-NLS-1$ } } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { JavaPlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } protected void smartPaste(IDocument document, DocumentCommand command) { String lineDelimiter= getLineDelimiter(document); try { String pastedText= command.text; Assert.isNotNull(pastedText); Assert.isTrue(pastedText.length() > 1); String strippedParagraph= stripIndent(pastedText, lineDelimiter); // check selection int offset= command.offset; int line= document.getLineOfOffset(offset); int lineOffset= document.getLineOffset(line); // format String prefix= document.get(lineOffset, offset - lineOffset); String blockIndent= getIndent(document, command); String indent= blockIndent == null ? "" : blockIndent + createIndent(1); //$NON-NLS-1$ // add one indent level boolean formatFirstLine= prefix.trim().length() == 0; String formattedParagraph= format(strippedParagraph, indent, lineDelimiter, formatFirstLine); // paste if (formatFirstLine) { int end= command.offset + command.length; command.offset= lineOffset; command.length= end - command.offset; } command.text= formattedParagraph; } catch (BadLocationException e) { JavaPlugin.log(e); } } /** * Returns the displayed width of a string, taking in account the displayed tab width. * The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string) { final int tabWidth= JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); int column= 0; for (int i= 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else column++; return column; } private String getIndent(IDocument d, DocumentCommand c) { if (c.offset < 0) return null; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1 && indLine != line) // take the indent of the found line return getIndentOfLine(d, indLine); } catch (BadLocationException excp) { System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message1")); //$NON-NLS-1$ } return null; } private static final class LineIterator implements Iterator { /** The document to iterator over. */ private final IDocument fDocument; /** The line index. */ private int fLineIndex; /** * Creates a line iterator. */ public LineIterator(String string) { fDocument= new Document(string); } /* * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return fLineIndex != fDocument.getNumberOfLines(); } /* * @see java.util.Iterator#next() */ public Object next() { try { IRegion region= fDocument.getLineInformation(fLineIndex++); return fDocument.get(region.getOffset(), region.getLength()); } catch (BadLocationException e) { JavaPlugin.log(e); throw new NoSuchElementException(); } } /* * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } private static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } private static String createIndent(int level) { StringBuffer buffer= new StringBuffer(); if (useSpaces()) { int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); int width= level * tabWidth; for (int i= 0; i != width; ++i) buffer.append(' '); } else { buffer.append('\t'); } return buffer.toString(); } private static String createPrefix(int displayedWidth) { StringBuffer buffer= new StringBuffer(); if (useSpaces()) { for (int i= 0; i != displayedWidth; ++i) buffer.append(' '); } else { int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); int div= displayedWidth / tabWidth; int mod= displayedWidth % tabWidth; for (int i= 0; i != div; ++i) buffer.append('\t'); for (int i= 0; i != mod; ++i) buffer.append(' '); } return buffer.toString(); } private String stripIndent(String paragraph, String lineDelimiter) { final StringBuffer buffer= new StringBuffer(); // determine minimum indent width int minIndentWidth= Integer.MAX_VALUE; for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); String trimmedLine= line.trim(); if (trimmedLine.length() == 0) continue; int index= line.indexOf(trimmedLine); String indent= line.substring(0, index); int width= calculateDisplayedWidth(indent); minIndentWidth= Math.min(minIndentWidth, width); } // strip prefixes for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); String trimmedLine= line.trim(); if (trimmedLine.length() != 0) { int index= line.indexOf(trimmedLine); String indent= line.substring(0, index); int width= calculateDisplayedWidth(indent); int strippedWidth= width - minIndentWidth; String prefix= createPrefix(strippedWidth); buffer.append(prefix); buffer.append(trimmedLine); } if (iterator.hasNext()) buffer.append(lineDelimiter); } return buffer.toString(); } private String format(String paragraph, String indent, String lineDelimiter, boolean indentFirstLine) { final StringBuffer buffer= new StringBuffer(); for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); if (indentFirstLine && line.trim().length() != 0) buffer.append(indent); else indentFirstLine= true; buffer.append(line); if (iterator.hasNext()) buffer.append(lineDelimiter); } return buffer.toString(); } private String getOneIndentLevel() { return String.valueOf('\t'); } /** * Returns whether the text ends with one of the given search strings. */ private boolean endsWithDelimiter(IDocument d, String txt) { String[] delimiters= d.getLegalLineDelimiters(); for (int i= 0; i < delimiters.length; i++) { if (txt.endsWith(delimiters[i])) return true; } return false; } private boolean equalsDelimiter(IDocument d, String txt) { String[] delimiters= d.getLegalLineDelimiters(); for (int i= 0; i < delimiters.length; i++) { if (txt.equals(delimiters[i])) return true; } return false; } private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) { if (command.text.charAt(0) == '}') smartInsertAfterBracket(document, command); } /* * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand(IDocument d, DocumentCommand c) { if (c.length == 0 && c.text != null && equalsDelimiter(d, c.text)) smartIndentAfterNewLine(d, c); else if (c.text.length() == 1) smartIndentAfterBlockDelimiter(d, c); else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE)) smartPaste(d, c); } private static boolean useSpaces() { return JavaCore.SPACE.equals(JavaCore.getOptions().get(JavaCore.FORMATTER_TAB_CHAR)); } }
26,547
Bug 26547 Automatic closing of strings is not smart enough
Trying to add strings around an existing identifier is highly annoying when the Automatically close Strings option is set. For example, when I try to add Strings around: System.out.println(a) before a then I get two quotes. I suggest the rule to not close a string when there is a letter that belongs to an identifier to the left or right.
resolved fixed
7992adc
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-18T19:00:39Z
2002-11-16T18:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.Position; 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.SourceViewerConfiguration; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.tasklist.TaskList; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction; import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionSourceViewer; import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; /** * Java specific text editor. */ public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant { interface ITextConverter { void customizeDocumentCommand(IDocument document, DocumentCommand command); }; class AdaptedRulerLayout extends Layout { protected int fGap; protected AdaptedSourceViewer fAdaptedSourceViewer; protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) { fGap= gap; fAdaptedSourceViewer= asv; } protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { Control[] children= composite.getChildren(); Point s= children[children.length - 1].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache); if (fAdaptedSourceViewer.isVerticalRulerVisible()) s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap; return s; } protected void layout(Composite composite, boolean flushCache) { Rectangle clArea= composite.getClientArea(); if (fAdaptedSourceViewer.isVerticalRulerVisible()) { StyledText textWidget= fAdaptedSourceViewer.getTextWidget(); Rectangle trim= textWidget.computeTrim(0, 0, 0, 0); int scrollbarHeight= trim.height; IVerticalRuler vr= fAdaptedSourceViewer.getVerticalRuler(); int vrWidth=vr.getWidth(); int orWidth= 0; if (fAdaptedSourceViewer.isOverviewRulerVisible()) { OverviewRuler or= fAdaptedSourceViewer.getOverviewRuler(); orWidth= or.getWidth(); or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight, orWidth, clArea.height - 3*scrollbarHeight); } textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth - 2*fGap, clArea.height); vr.getControl().setBounds(0, 0, vrWidth, clArea.height - scrollbarHeight); } else { StyledText textWidget= fAdaptedSourceViewer.getTextWidget(); textWidget.setBounds(0, 0, clArea.width, clArea.height); } } }; class AdaptedSourceViewer extends JavaCorrectionSourceViewer { private List fTextConverters; private OverviewRuler fOverviewRuler; private boolean fIsOverviewRulerVisible; private boolean fIgnoreTextConverters= false; private IVerticalRuler fCachedVerticalRuler; private boolean fCachedIsVerticalRulerVisible; public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { super(parent, ruler, styles, CompilationUnitEditor.this); fCachedVerticalRuler= ruler; fCachedIsVerticalRulerVisible= (ruler != null); fOverviewRuler= new OverviewRuler(VERTICAL_RULER_WIDTH); delayedCreateControl(parent, styles); } /* * @see ISourceViewer#showAnnotations(boolean) */ public void showAnnotations(boolean show) { fCachedIsVerticalRulerVisible= (show && fCachedVerticalRuler != null); super.showAnnotations(show); } public IContentAssistant getContentAssistant() { return fContentAssistant; } /* * @see ITextOperationTarget#doOperation(int) */ public void doOperation(int operation) { if (getTextWidget() == null) return; switch (operation) { case CONTENTASSIST_PROPOSALS: String msg= fContentAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case UNDO: fIgnoreTextConverters= true; break; case REDO: fIgnoreTextConverters= true; break; } super.doOperation(operation); } public void insertTextConverter(ITextConverter textConverter, int index) { throw new UnsupportedOperationException(); } public void addTextConverter(ITextConverter textConverter) { if (fTextConverters == null) { fTextConverters= new ArrayList(1); fTextConverters.add(textConverter); } else if (!fTextConverters.contains(textConverter)) fTextConverters.add(textConverter); } public void removeTextConverter(ITextConverter textConverter) { if (fTextConverters != null) { fTextConverters.remove(textConverter); if (fTextConverters.size() == 0) fTextConverters= null; } } /* * @see TextViewer#customizeDocumentCommand(DocumentCommand) */ protected void customizeDocumentCommand(DocumentCommand command) { super.customizeDocumentCommand(command); if (!fIgnoreTextConverters && fTextConverters != null) { for (Iterator e = fTextConverters.iterator(); e.hasNext();) ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command); } fIgnoreTextConverters= false; } public IVerticalRuler getVerticalRuler() { return fCachedVerticalRuler; } public boolean isVerticalRulerVisible() { return fCachedIsVerticalRulerVisible; } public OverviewRuler getOverviewRuler() { return fOverviewRuler; } /* * @see TextViewer#createControl(Composite, int) */ protected void createControl(Composite parent, int styles) { // do nothing here } protected void delayedCreateControl(Composite parent, int styles) { //create the viewer super.createControl(parent, styles); Control control= getControl(); if (control instanceof Composite) { Composite composite= (Composite) control; composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this)); fOverviewRuler.createControl(composite, this); } } public void hideOverviewRuler() { fIsOverviewRulerVisible= false; Control control= getControl(); if (control instanceof Composite) { Composite composite= (Composite) control; composite.layout(); } } public void showOverviewRuler() { fIsOverviewRulerVisible= true; Control control= getControl(); if (control instanceof Composite) { Composite composite= (Composite) control; composite.layout(); } } public boolean isOverviewRulerVisible() { return fIsOverviewRulerVisible; } /* * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int) */ public void setDocument(IDocument document, IAnnotationModel annotationModel, int visibleRegionOffset, int visibleRegionLength) { super.setDocument(document, annotationModel, visibleRegionOffset, visibleRegionLength); fOverviewRuler.setModel(annotationModel); } // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 public void updateIndentationPrefixes() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(this); for (int i= 0; i < types.length; i++) { String[] prefixes= configuration.getIndentPrefixes(this, types[i]); if (prefixes != null && prefixes.length > 0) setIndentPrefixes(prefixes, types[i]); } } /* * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) */ public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester); } }; static class TabConverter implements ITextConverter { private int fTabRatio; private ILineTracker fLineTracker; public TabConverter() { } public void setNumberOfSpacesPerTab(int ratio) { fTabRatio= ratio; } public void setLineTracker(ILineTracker lineTracker) { fLineTracker= lineTracker; } private int insertTabString(StringBuffer buffer, int offsetInLine) { if (fTabRatio == 0) return 0; int remainder= offsetInLine % fTabRatio; remainder= fTabRatio - remainder; for (int i= 0; i < remainder; i++) buffer.append(' '); return remainder; } public void customizeDocumentCommand(IDocument document, DocumentCommand command) { String text= command.text; if (text == null) return; int index= text.indexOf('\t'); if (index > -1) { StringBuffer buffer= new StringBuffer(); fLineTracker.set(command.text); int lines= fLineTracker.getNumberOfLines(); try { for (int i= 0; i < lines; i++) { int offset= fLineTracker.getLineOffset(i); int endOffset= offset + fLineTracker.getLineLength(i); String line= text.substring(offset, endOffset); int position= 0; if (i == 0) { IRegion firstLine= document.getLineInformationOfOffset(command.offset); position= command.offset - firstLine.getOffset(); } int length= line.length(); for (int j= 0; j < length; j++) { char c= line.charAt(j); if (c == '\t') { position += insertTabString(buffer, position); } else { buffer.append(c); ++ position; } } } command.text= buffer.toString(); } catch (BadLocationException x) { } } } }; private class PropertyChangeListener implements IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { handlePreferencePropertyChanged(event); } } /* Preference key for code formatter tab size */ private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; /** Preference key for matching brackets */ private final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS; /** Preference key for matching brackets color */ private final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; /** Preference key for highlighting current line */ private final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE; /** Preference key for highlight color of current line */ private final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR; /** Preference key for showing print marging ruler */ private final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN; /** Preference key for print margin ruler color */ private final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR; /** Preference key for print margin ruler column */ private final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN; /** Preference key for inserting spaces rather than tabs */ private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS; /** Preference key for error indication */ private final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION; /** Preference key for error color */ private final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; /** Preference key for warning indication */ private final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION; /** Preference key for warning color */ private final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; /** Preference key for task indication */ private final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION; /** Preference key for task color */ private final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR; /** Preference key for bookmark indication */ private final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION; /** Preference key for bookmark color */ private final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR; /** Preference key for search result indication */ private final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION; /** Preference key for search result color */ private final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR; /** Preference key for unknown annotation indication */ private final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION; /** Preference key for unknown annotation color */ private final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR; /** Preference key for linked position color */ private final static String LINKED_POSITION_COLOR= PreferenceConstants.EDITOR_LINKED_POSITION_COLOR; /** Preference key for shwoing the overview ruler */ private final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER; /** Preference key for error indication in overview ruler */ private final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER; /** Preference key for warning indication in overview ruler */ private final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER; /** Preference key for task indication in overview ruler */ private final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER; /** Preference key for bookmark indication in overview ruler */ private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER; /** Preference key for search result indication in overview ruler */ private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; /** Preference key for unknown annotation indication in overview ruler */ private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER; /** Preference key for automatically closing strings */ private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS; /** Preference key for automatically wrapping Java strings */ private final static String WRAP_STRINGS= PreferenceConstants.EDITOR_WRAP_STRINGS; /** Preference key for automatically closing brackets and parenthesis */ private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS; /** Preference key for automatically closing javadocs and comments */ private final static String CLOSE_JAVADOCS= PreferenceConstants.EDITOR_CLOSE_JAVADOCS; /** Preference key for automatically adding javadoc tags */ private final static String ADD_JAVADOC_TAGS= PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS; /** Preference key for automatically formatting javadocs */ private final static String FORMAT_JAVADOCS= PreferenceConstants.EDITOR_FORMAT_JAVADOCS; /** Preference key for smart paste */ private final static String SMART_PASTE= PreferenceConstants.EDITOR_SMART_PASTE; private final static class AnnotationInfo { public String fColorPreference; public String fOverviewRulerPreference; public String fEditorPreference; }; private final static Map ANNOTATION_MAP; static { AnnotationInfo info; ANNOTATION_MAP= new HashMap(); info= new AnnotationInfo(); info.fColorPreference= TASK_INDICATION_COLOR; info.fOverviewRulerPreference= TASK_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= TASK_INDICATION; ANNOTATION_MAP.put(AnnotationType.TASK, info); info= new AnnotationInfo(); info.fColorPreference= ERROR_INDICATION_COLOR; info.fOverviewRulerPreference= ERROR_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= ERROR_INDICATION; ANNOTATION_MAP.put(AnnotationType.ERROR, info); info= new AnnotationInfo(); info.fColorPreference= WARNING_INDICATION_COLOR; info.fOverviewRulerPreference= WARNING_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= WARNING_INDICATION; ANNOTATION_MAP.put(AnnotationType.WARNING, info); info= new AnnotationInfo(); info.fColorPreference= BOOKMARK_INDICATION_COLOR; info.fOverviewRulerPreference= BOOKMARK_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= BOOKMARK_INDICATION; ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info); info= new AnnotationInfo(); info.fColorPreference= SEARCH_RESULT_INDICATION_COLOR; info.fOverviewRulerPreference= SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= SEARCH_RESULT_INDICATION; ANNOTATION_MAP.put(AnnotationType.SEARCH_RESULT, info); info= new AnnotationInfo(); info.fColorPreference= UNKNOWN_INDICATION_COLOR; info.fOverviewRulerPreference= UNKNOWN_INDICATION_IN_OVERVIEW_RULER; info.fEditorPreference= UNKNOWN_INDICATION; ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info); }; private final static AnnotationType[] ANNOTATION_LAYERS= new AnnotationType[] { AnnotationType.UNKNOWN, AnnotationType.BOOKMARK, AnnotationType.TASK, AnnotationType.SEARCH_RESULT, AnnotationType.WARNING, AnnotationType.ERROR }; /** 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 paint manager */ private PaintManager fPaintManager; /** The editor's bracket painter */ private BracketPainter fBracketPainter; /** The editor's bracket matcher */ private JavaPairMatcher fBracketMatcher; /** The editor's line painter */ private LinePainter fLinePainter; /** The editor's print margin ruler painter */ private PrintMarginPainter fPrintMarginPainter; /** The editor's problem painter */ private ProblemPainter fProblemPainter; /** The editor's tab converter */ private TabConverter fTabConverter; /** History for structure select action */ private SelectionHistory fSelectionHistory; /** The preference property change listener for java core. */ private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener(); /** The remembered java element */ private IJavaElement fRememberedElement; /** The remembered selection */ private ITextSelection fRememberedSelection; /** The remembered java element offset */ private int fRememberedElementOffset; /** The bracket inserter. */ private BracketInserter fBracketInserter= new BracketInserter(); /** The standard action groups added to the menu */ private GenerateActionGroup fGenerateActionGroup; private CompositeActionGroup fContextMenuGroup; /** * Creates a new compilation unit editor. */ public CompilationUnitEditor() { super(); setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider()); setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$ setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$ // don't set help contextId, we install our own help context fSavePolicy= null; fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this); } /* * @see AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, JavaCorrectionSourceViewer.CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction("ContentAssistProposal", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT); setAction("Comment", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT); setAction("Uncomment", action); //$NON-NLS-1$ action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT); setAction("Format", action); //$NON-NLS-1$ markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$ markAsStateDependentAction("Comment", true); //$NON-NLS-1$ markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ markAsStateDependentAction("Format", true); //$NON-NLS-1$ action= new GotoMatchingBracketAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER); setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); fSelectionHistory= new SelectionHistory(this); action= new StructureSelectEnclosingAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING); setAction(StructureSelectionAction.ENCLOSING, action); action= new StructureSelectNextAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT); setAction(StructureSelectionAction.NEXT, action); action= new StructureSelectPreviousAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS); setAction(StructureSelectionAction.PREVIOUS, action); StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory); historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST); setAction(StructureSelectionAction.HISTORY, historyAction); fSelectionHistory.setHistoryAction(historyAction); fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); fActionGroups.addGroup(rg); fActionGroups.addGroup(fGenerateActionGroup); // We have to keep the context menu group separate to have better control over positioning fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup, rg, new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)}); } /* * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementAt(int offset) { return getElementAt(offset, true); } /** * Returns the most narrow element including the given offset. If <code>reconcile</code> * is <code>true</code> the editor's input element is reconciled in advance. If it is * <code>false</code> this method only returns a result if the editor's input element * does not need to be reconciled. * * @param offset the offset included by the retrieved element * @param reconcile <code>true</code> if working copy should be reconciled */ protected IJavaElement getElementAt(int offset, boolean reconcile) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { if (reconcile) { synchronized (unit) { unit.reconcile(); } return unit.getElementAt(offset); } else if (unit.isConsistent()) return unit.getElementAt(offset); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /* * @see JavaEditor#getCorrespondingElement(IJavaElement) */ protected IJavaElement getCorrespondingElement(IJavaElement element) { try { return EditorUtility.getWorkingCopy(element, true); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } return null; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$ ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /* * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) */ protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { if (page != null) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); page.setInput(manager.getWorkingCopy(input)); } } /* * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor) */ protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p; cp.setSavePolicy(fSavePolicy); } try { super.performSaveOperation(operation, progressMonitor); } finally { if (p instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p; cp.setSavePolicy(null); } } } /* * @see AbstractTextEditor#doSave(IProgressMonitor) */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) { // editor has been closed return; } if (p.isDeleted(getEditorInput())) { if (isSaveAsAllowed()) { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(progressMonitor); } else { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Missing resources. */ Shell shell= getSite().getShell(); MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { setStatusLineErrorMessage(null); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { performSaveOperation(createSaveOperation(false), progressMonitor); } } else performSaveOperation(createSaveOperation(false), progressMonitor); } } /** * Jumps to the error next according to the given direction. */ public void gotoError(boolean forward) { ISelectionProvider provider= getSelectionProvider(); ITextSelection s= (ITextSelection) provider.getSelection(); Position errorPosition= new Position(0, 0); IProblemAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition); if (nextError != null) { IMarker marker= null; if (nextError instanceof MarkerAnnotation) marker= ((MarkerAnnotation) nextError).getMarker(); else { Iterator e= nextError.getOverlaidIterator(); if (e != null) { while (e.hasNext()) { Object o= e.next(); if (o instanceof MarkerAnnotation) { marker= ((MarkerAnnotation) o).getMarker(); break; } } } } if (marker != null) { IWorkbenchPage page= getSite().getPage(); IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$ if (view instanceof TaskList) { StructuredSelection ss= new StructuredSelection(marker); ((TaskList) view).setSelection(ss, true); } } selectAndReveal(errorPosition.getOffset(), errorPosition.getLength()); setStatusLineErrorMessage(nextError.getMessage()); } else { setStatusLineErrorMessage(null); } } /** * Jumps to the matching bracket. */ public void gotoMatchingBracket() { if (fBracketMatcher == null) fBracketMatcher= new JavaPairMatcher(new char[] { '{', '}', '(', ')', '[', ']' }); ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); if (document == null) return; ISelectionProvider provider= getSelectionProvider(); ITextSelection selection= (ITextSelection) provider.getSelection(); int selectionLength= Math.abs(selection.getLength()); if (selectionLength > 1) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } IRegion region= fBracketMatcher.match(document, selection.getOffset()); if (region == null) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } int offset= region.getOffset(); int length= region.getLength(); if (length < 1) return; int anchor= fBracketMatcher.getAnchor(); int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset : offset + length - 1; IRegion visibleRegion= sourceViewer.getVisibleRegion(); if (targetOffset < visibleRegion.getOffset() || targetOffset >= visibleRegion.getOffset() + visibleRegion.getLength()) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } sourceViewer.setSelectedRange(targetOffset, selectionLength); sourceViewer.revealRange(targetOffset, selectionLength); } /** * Ses the given message as error message to this editor's status line. * @param msg message to be set */ protected void setStatusLineErrorMessage(String msg) { IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(true, msg, null); } private IProblemAnnotation getNextError(int offset, boolean forward, Position errorPosition) { IProblemAnnotation nextError= null; Position nextErrorPosition= null; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= 0; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= new ProblemAnnotationIterator(model, false); while (e.hasNext()) { IProblemAnnotation a= (IProblemAnnotation) e.next(); if (a.hasOverlay() || !a.isProblem()) continue; Position p= model.getPosition((Annotation) a); if (!p.includes(offset)) { int currentDistance= 0; if (forward) { currentDistance= p.getOffset() - offset; if (currentDistance < 0) currentDistance= endOfDocument - offset + p.getOffset(); } else { currentDistance= offset - p.getOffset(); if (currentDistance < 0) currentDistance= offset + endOfDocument - p.getOffset(); } if (nextError == null || currentDistance < distance) { distance= currentDistance; nextError= a; nextErrorPosition= p; } } } if (nextErrorPosition != null) { errorPosition.setOffset(nextErrorPosition.getOffset()); errorPosition.setLength(nextErrorPosition.getLength()); } return nextError; } /* * @see AbstractTextEditor#isSaveAsAllowed() */ public boolean isSaveAsAllowed() { return true; } /** * The compilation unit editor implementation of this <code>AbstractTextEditor</code> * method asks the user for the workspace path of a file resource and saves the document * there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); IEditorInput input = getEditorInput(); SaveAsDialog dialog= new SaveAsDialog(shell); IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; if (original != null) dialog.setOriginalFile(original); dialog.create(); IDocumentProvider provider= getDocumentProvider(); if (provider == null) { // editor has been programmatically closed while the dialog was open return; } if (provider.isDeleted(input) && original != null) { String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ dialog.setErrorMessage(null); dialog.setMessage(message, IMessageProvider.WARNING); } if (dialog.open() == Dialog.CANCEL) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IPath filePath= dialog.getResult(); if (filePath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IWorkspace workspace= ResourcesPlugin.getWorkspace(); IFile file= workspace.getRoot().getFile(filePath); final IEditorInput newInput= new FileEditorInput(file); WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(final IProgressMonitor monitor) throws CoreException { getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); } }; boolean success= false; try { provider.aboutToChange(newInput); new ProgressMonitorDialog(shell).run(false, true, op); success= true; } catch (InterruptedException x) { } catch (InvocationTargetException x) { Throwable t= x.getTargetException(); if (t instanceof CoreException) { CoreException cx= (CoreException) t; ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ } else { MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { provider.changed(newInput); if (success) setInput(newInput); } if (progressMonitor != null) progressMonitor.setCanceled(!success); } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); configureTabConverter(); } private void startBracketHighlighting() { if (fBracketPainter == null) { ISourceViewer sourceViewer= getSourceViewer(); fBracketPainter= new BracketPainter(sourceViewer); fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); fPaintManager.addPainter(fBracketPainter); } } private void stopBracketHighlighting() { if (fBracketPainter != null) { fPaintManager.removePainter(fBracketPainter); fBracketPainter.deactivate(true); fBracketPainter.dispose(); fBracketPainter= null; } } private boolean isBracketHighlightingEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(MATCHING_BRACKETS); } private void startLineHighlighting() { if (fLinePainter == null) { ISourceViewer sourceViewer= getSourceViewer(); fLinePainter= new LinePainter(sourceViewer); fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR)); fPaintManager.addPainter(fLinePainter); } } private void stopLineHighlighting() { if (fLinePainter != null) { fPaintManager.removePainter(fLinePainter); fLinePainter.deactivate(true); fLinePainter.dispose(); fLinePainter= null; } } private boolean isLineHighlightingEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(CURRENT_LINE); } private void showPrintMargin() { if (fPrintMarginPainter == null) { fPrintMarginPainter= new PrintMarginPainter(getSourceViewer()); fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); fPaintManager.addPainter(fPrintMarginPainter); } } private void hidePrintMargin() { if (fPrintMarginPainter != null) { fPaintManager.removePainter(fPrintMarginPainter); fPrintMarginPainter.deactivate(true); fPrintMarginPainter.dispose(); fPrintMarginPainter= null; } } private boolean isPrintMarginVisible() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(PRINT_MARGIN); } private void startAnnotationIndication(AnnotationType annotationType) { if (fProblemPainter == null) { fProblemPainter= new ProblemPainter(this, getSourceViewer()); fPaintManager.addPainter(fProblemPainter); } fProblemPainter.setColor(annotationType, getColor(annotationType)); fProblemPainter.paintAnnotations(annotationType, true); fProblemPainter.paint(IPainter.CONFIGURATION); } private void shutdownAnnotationIndication() { if (fProblemPainter != null) { if (!fProblemPainter.isPaintingAnnotations()) { fPaintManager.removePainter(fProblemPainter); fProblemPainter.deactivate(true); fProblemPainter.dispose(); fProblemPainter= null; } else { fProblemPainter.paint(IPainter.CONFIGURATION); } } } private void stopAnnotationIndication(AnnotationType annotationType) { if (fProblemPainter != null) { fProblemPainter.paintAnnotations(annotationType, false); shutdownAnnotationIndication(); } } private boolean isAnnotationIndicationEnabled(AnnotationType annotationType) { IPreferenceStore store= getPreferenceStore(); AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType); if (info != null) return store.getBoolean(info.fEditorPreference); return false; } private boolean isAnnotationIndicationInOverviewRulerEnabled(AnnotationType annotationType) { IPreferenceStore store= getPreferenceStore(); AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType); if (info != null) return store.getBoolean(info.fOverviewRulerPreference); return false; } private void showAnnotationIndicationInOverviewRuler(AnnotationType annotationType, boolean show) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); OverviewRuler ruler= asv.getOverviewRuler(); if (ruler != null) { ruler.setColor(annotationType, getColor(annotationType)); ruler.showAnnotation(annotationType, show); ruler.update(); } } private void setColorInOverviewRuler(AnnotationType annotationType, Color color) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); OverviewRuler ruler= asv.getOverviewRuler(); if (ruler != null) { ruler.setColor(annotationType, color); ruler.update(); } } private void configureTabConverter() { if (fTabConverter != null) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof CompilationUnitDocumentProvider) { CompilationUnitDocumentProvider cup= (CompilationUnitDocumentProvider) provider; fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); } } } private int getTabSize() { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); return preferences.getInt(CODE_FORMATTER_TAB_SIZE); } private void startTabConversion() { if (fTabConverter == null) { fTabConverter= new TabConverter(); configureTabConverter(); fTabConverter.setNumberOfSpacesPerTab(getTabSize()); AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.addTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); } } private void stopTabConversion() { if (fTabConverter != null) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.removeTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); fTabConverter= null; } } private boolean isTabConversionEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(SPACES_FOR_TABS); } private void showOverviewRuler() { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.showOverviewRuler(); OverviewRuler overviewRuler= asv.getOverviewRuler(); if (overviewRuler != null) { for (int i= 0; i < ANNOTATION_LAYERS.length; i++) { AnnotationType type= ANNOTATION_LAYERS[i]; overviewRuler.setLayer(type, i); if (isAnnotationIndicationInOverviewRulerEnabled(type)) showAnnotationIndicationInOverviewRuler(type, true); } } } private void hideOverviewRuler() { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.hideOverviewRuler(); } private boolean isOverviewRulerVisible() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(OVERVIEW_RULER); } private Color getColor(String key) { RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), key); return getColor(rgb); } private Color getColor(RGB rgb) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private Color getColor(AnnotationType annotationType) { AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType); if (info != null) return getColor(info.fColorPreference); return null; } /* * @see AbstractTextEditor#dispose() */ public void dispose() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter); if (fPropertyChangeListener != null) { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fJavaEditorErrorTickUpdater != null) { fJavaEditorErrorTickUpdater.dispose(); fJavaEditorErrorTickUpdater= null; } if (fSelectionHistory != null) fSelectionHistory.dispose(); if (fPaintManager != null) { fPaintManager.dispose(); fPaintManager= null; } if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } /* * @see AbstractTextEditor#createPartControl(Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); fPaintManager= new PaintManager(getSourceViewer()); if (isBracketHighlightingEnabled()) startBracketHighlighting(); if (isLineHighlightingEnabled()) startLineHighlighting(); if (isPrintMarginVisible()) showPrintMargin(); Iterator e= ANNOTATION_MAP.keySet().iterator(); while (e.hasNext()) { AnnotationType type= (AnnotationType) e.next(); if (isAnnotationIndicationEnabled(type)) startAnnotationIndication(type); } if (isTabConversionEnabled()) startTabConversion(); if (isOverviewRulerVisible()) showOverviewRuler(); Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(fPropertyChangeListener); IPreferenceStore preferenceStore= getPreferenceStore(); boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS); boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS); fBracketInserter.setCloseBracketsEnabled(closeBrackets); fBracketInserter.setCloseStringsEnabled(closeStrings); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter); } private static char getPeerCharacter(char character) { switch (character) { case '(': return ')'; case ')': return '('; case '[': return ']'; case ']': return '['; case '"': return character; default: throw new IllegalArgumentException(); } } private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { final char fExitCharacter; public ExitPolicy(char exitCharacter) { fExitCharacter= exitCharacter; } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (manager.anyPositionIncludes(offset, length)) return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false); else return new ExitFlags(LinkedPositionUI.COMMIT, true); } switch (event.character) { case '\b': if (manager.getFirstPosition().length == 0) return new ExitFlags(0, false); else return null; case '\n': case '\r': return new ExitFlags(LinkedPositionUI.COMMIT, true); default: return null; } } } private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener { private boolean fCloseBrackets= true; private boolean fCloseStrings= true; private int fOffset; private int fLength; public void setCloseBracketsEnabled(boolean enabled) { fCloseBrackets= enabled; } public void setCloseStringsEnabled(boolean enabled) { fCloseStrings= enabled; } private boolean isResfOfLineEmpty(IDocument document, int offset) { if (offset == document.getLength()) return true; try { IRegion line= document.getLineInformationOfOffset(offset); String string= document.get(offset, line.getOffset() + line.getLength() - offset); for (int i= 0; i < string.length(); i++) if (!Character.isWhitespace(string.charAt(i))) return false; return true; } catch (BadLocationException e) { return true; } } /* * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ public void verifyKey(VerifyEvent event) { if (!event.doit) return; final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); final Point selection= sourceViewer.getSelectedRange(); final int offset= selection.x; final int length= selection.y; switch (event.character) { case '(': case '[': if (!fCloseBrackets || !isResfOfLineEmpty(document, offset + length)) return; case '"': if (event.character == '"' && !fCloseStrings) return; try { ITypedRegion partition= document.getPartition(offset); if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset) return; final char character= event.character; final char closingCharacter= getPeerCharacter(character); final StringBuffer buffer= new StringBuffer(); buffer.append(character); buffer.append(closingCharacter); document.replace(offset, length, buffer.toString()); LinkedPositionManager manager= new LinkedPositionManager(document); manager.addPosition(offset + 1, 0); fOffset= offset; fLength= 2; LinkedPositionUI editor= new LinkedPositionUI(sourceViewer, manager); editor.setCancelListener(this); editor.setExitPolicy(new ExitPolicy(closingCharacter)); editor.setFinalCaretOffset(offset + 2); editor.enter(); IRegion newSelection= editor.getSelectedRegion(); sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength()); event.doit= false; } catch (BadLocationException e) { } break; } } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean) */ public void exit(boolean accept) { if (accept) return; // remove brackets try { final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); document.replace(fOffset, fLength, null); } catch (BadLocationException e) { } } } protected AnnotationType getAnnotationType(String preferenceKey) { Iterator e= ANNOTATION_MAP.keySet().iterator(); while (e.hasNext()) { AnnotationType type= (AnnotationType) e.next(); AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type); if (info != null) { if (preferenceKey.equals(info.fColorPreference) || preferenceKey.equals(info.fEditorPreference) || preferenceKey.equals(info.fOverviewRulerPreference)) return type; } } return null; } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CLOSE_BRACKETS.equals(p)) { fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p)); return; } if (CLOSE_STRINGS.equals(p)) { fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p)); return; } if (SPACES_FOR_TABS.equals(p)) { if (isTabConversionEnabled()) startTabConversion(); else stopTabConversion(); return; } if (MATCHING_BRACKETS.equals(p)) { if (isBracketHighlightingEnabled()) startBracketHighlighting(); else stopBracketHighlighting(); return; } if (MATCHING_BRACKETS_COLOR.equals(p)) { if (fBracketPainter != null) fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); return; } if (CURRENT_LINE.equals(p)) { if (isLineHighlightingEnabled()) startLineHighlighting(); else stopLineHighlighting(); return; } if (CURRENT_LINE_COLOR.equals(p)) { if (fLinePainter != null) { stopLineHighlighting(); startLineHighlighting(); } return; } if (PRINT_MARGIN.equals(p)) { if (isPrintMarginVisible()) showPrintMargin(); else hidePrintMargin(); return; } if (PRINT_MARGIN_COLOR.equals(p)) { if (fPrintMarginPainter != null) fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); return; } if (PRINT_MARGIN_COLUMN.equals(p)) { if (fPrintMarginPainter != null) fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); return; } if (OVERVIEW_RULER.equals(p)) { if (isOverviewRulerVisible()) showOverviewRuler(); else hideOverviewRuler(); return; } AnnotationType type= getAnnotationType(p); if (type != null) { AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type); if (info.fColorPreference.equals(p)) { Color color= getColor(type); if (fProblemPainter != null) { fProblemPainter.setColor(type, color); fProblemPainter.paint(IPainter.CONFIGURATION); } setColorInOverviewRuler(type, color); return; } if (info.fEditorPreference.equals(p)) { if (isAnnotationIndicationEnabled(type)) startAnnotationIndication(type); else stopAnnotationIndication(type); return; } if (info.fOverviewRulerPreference.equals(p)) { if (isAnnotationIndicationInOverviewRulerEnabled(type)) showAnnotationIndicationInOverviewRuler(type, true); else showAnnotationIndicationInOverviewRuler(type, false); return; } } IContentAssistant c= asv.getContentAssistant(); if (c instanceof ContentAssistant) ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event); } } finally { super.handlePreferenceStoreChanged(event); } } /** * Handles a property change event describing a change * of the java core's preferences and updates the preference * related editor properties. * * @param event the property change event */ protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CODE_FORMATTER_TAB_SIZE.equals(p)) { asv.updateIndentationPrefixes(); if (fTabConverter != null) fTabConverter.setNumberOfSpacesPerTab(getTabSize()); } } } /* * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { String p= event.getProperty(); boolean affects=MATCHING_BRACKETS_COLOR.equals(p) || CURRENT_LINE_COLOR.equals(p) || ERROR_INDICATION_COLOR.equals(p) || WARNING_INDICATION_COLOR.equals(p) || TASK_INDICATION_COLOR.equals(p); return affects ? affects : super.affectsTextPresentation(event); } /* * @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return new AdaptedSourceViewer(parent, ruler, styles); } /* * @see JavaEditor#synchronizeOutlinePageSelection() */ public void synchronizeOutlinePageSelection() { if (isEditingScriptRunning()) return; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null || fOutlinePage == null) return; StyledText styledText= sourceViewer.getTextWidget(); if (styledText == null) return; int offset= sourceViewer.getVisibleRegion().getOffset(); int caret= offset + styledText.getCaretOffset(); IJavaElement element= getElementAt(caret, false); ISourceReference reference= getSourceReference(element, caret); if (reference != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select(reference); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } } private ISourceReference getSourceReference(IJavaElement element, int offset) { if ( !(element instanceof ISourceReference)) return null; if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { IImportDeclaration declaration= (IImportDeclaration) element; IImportContainer container= (IImportContainer) declaration.getParent(); ISourceRange srcRange= null; try { srcRange= container.getSourceRange(); } catch (JavaModelException e) { } if (srcRange != null && srcRange.getOffset() == offset) return container; } return (ISourceReference) element; } /* * @see IReconcilingParticipant#reconciled() */ public void reconciled() { if (!JavaEditorPreferencePage.synchronizeOutlineOnCursorMove()) { Shell shell= getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(new Runnable() { public void run() { synchronizeOutlinePageSelection(); } }); } } } protected void updateStateDependentActions() { super.updateStateDependentActions(); fGenerateActionGroup.editorStateChanged(); } /** * Returns the updated java element for the old java element. */ private IJavaElement findElement(IJavaElement element) { if (element == null) return null; IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { synchronized (unit) { unit.reconcile(); } IJavaElement[] findings= unit.findElements(element); if (findings != null && findings.length > 0) return findings[0]; } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /** * Returns the offset of the given Java element. */ private int getOffset(IJavaElement element) { if (element instanceof ISourceReference) { ISourceReference sr= (ISourceReference) element; try { ISourceRange srcRange= sr.getSourceRange(); if (srcRange != null) return srcRange.getOffset(); } catch (JavaModelException e) { } } return -1; } /* * @see AbstractTextEditor#rememberSelection() */ protected void rememberSelection() { ISelectionProvider sp= getSelectionProvider(); fRememberedSelection= (sp == null ? null : (ITextSelection) sp.getSelection()); if (fRememberedSelection != null) { fRememberedElement= getElementAt(fRememberedSelection.getOffset(), true); fRememberedElementOffset= getOffset(fRememberedElement); } } /* * @see AbstractTextEditor#restoreSelection() */ protected void restoreSelection() { try { if (getSourceViewer() == null || fRememberedSelection == null) return; IJavaElement newElement= findElement(fRememberedElement); int newOffset= getOffset(newElement); int offset= (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - fRememberedElementOffset : 0; selectAndReveal(offset + fRememberedSelection.getOffset(), fRememberedSelection.getLength()); } finally { fRememberedSelection= null; fRememberedElement= null; fRememberedElementOffset= -1; } } /* * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) */ protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { String oldExtension= ""; //$NON-NLS-1$ if (originalElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) originalElement).getFile(); if (file != null) { String ext= file.getFileExtension(); if (ext != null) oldExtension= ext; } } String newExtension= ""; //$NON-NLS-1$ if (movedElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) movedElement).getFile(); if (file != null) newExtension= file.getFileExtension(); } return oldExtension.equals(newExtension); } }
25,768
Bug 25768 Package Explorer flashes too much on refresh and delete
build I20021105 - extracted a zip containing 22 non-Java files (.mxsd files from Dejan) into org.eclipse.ui - in Package Explorer, refreshed org.eclipse.ui - it flashed alot while refreshing - selected the 22 files and deleted them - it flashed even more
resolved fixed
8d149b4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T09:02:14Z
2002-11-06T13:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerContentProvider.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.packageview; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Content provider for the PackageExplorer. * * <p> * Since 2.1 this content provider can provide the children for flat or hierarchical * layout. The hierarchical layout is done by delegating to the <code>PackageFragmentProvider</code>. * </p> * * @see org.eclipse.jdt.ui.StandardJavaElementContentProvider * @see org.eclipse.jdt.internal.ui.packageview.PackageFragmentProvider */ class PackageExplorerContentProvider extends StandardJavaElementContentProvider implements ITreeContentProvider, IElementChangedListener { protected TreeViewer fViewer; protected Object fInput; private boolean fIsFlatLayout; private PackageFragmentProvider fPackageFragmentProvider= new PackageFragmentProvider(); /** * Creates a new content provider for Java elements. */ public PackageExplorerContentProvider() { } /** * Creates a new content provider for Java elements. */ public PackageExplorerContentProvider(boolean provideMembers, boolean provideWorkingCopy) { super(provideMembers, provideWorkingCopy); } /* (non-Javadoc) * Method declared on IElementChangedListener. */ public void elementChanged(final ElementChangedEvent event) { try { processDelta(event.getDelta()); } catch(JavaModelException e) { JavaPlugin.log(e); } } /* (non-Javadoc) * Method declared on IContentProvider. */ public void dispose() { super.dispose(); JavaCore.removeElementChangedListener(this); fPackageFragmentProvider.dispose(); } // ------ Code which delegates to PackageFragmentProvider ------ private boolean needsToDelegate(Object element) { int type= -1; if (element instanceof IJavaElement) type= ((IJavaElement)element).getElementType(); return (!fIsFlatLayout && (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.JAVA_PROJECT)); } public Object[] getChildren(Object parentElement) { if (needsToDelegate(parentElement)) { Object[] packageFragments= fPackageFragmentProvider.getChildren(parentElement); return getWithParentsResources(packageFragments, parentElement); } else return super.getChildren(parentElement); } public Object getParent(Object child) { if (needsToDelegate(child)) { return fPackageFragmentProvider.getParent(child); } else return super.getParent(child); } /** * Returns the given objects with the resources of the parent. */ private Object[] getWithParentsResources(Object[] existingObject, Object parent) { Object[] objects= super.getChildren(parent); List list= new ArrayList(); // Add everything that is not a PackageFragment for (int i= 0; i < objects.length; i++) { Object object= objects[i]; if (!(object instanceof IPackageFragment)) { list.add(object); } } if (existingObject != null) list.addAll(Arrays.asList(existingObject)); return list.toArray(); } /* (non-Javadoc) * Method declared on IContentProvider. */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { super.inputChanged(viewer, oldInput, newInput); fPackageFragmentProvider.inputChanged(viewer, oldInput, newInput); fViewer= (TreeViewer)viewer; if (oldInput == null && newInput != null) { JavaCore.addElementChangedListener(this); } else if (oldInput != null && newInput == null) { JavaCore.removeElementChangedListener(this); } fInput= newInput; } // ------ delta processing ------ /** * Processes a delta recursively. When more than two children are affected the * tree is fully refreshed starting at this node. The delta is processed in the * current thread but the viewer updates are posted to the UI thread. */ public void processDelta(IJavaElementDelta delta) throws JavaModelException { int kind= delta.getKind(); int flags= delta.getFlags(); IJavaElement element= delta.getElement(); if (!fIsFlatLayout && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { fPackageFragmentProvider.processDelta(delta); IJavaElementDelta[] affectedChildren= delta.getAffectedChildren(); processAffectedChildren(affectedChildren); return; } if (!getProvideWorkingCopy() && isWorkingCopy(element)) return; if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT && !isOnClassPath((ICompilationUnit)element)) return; // handle open and closing of a solution or project if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) { postRefresh(element); return; } if (kind == IJavaElementDelta.REMOVED) { // when a working copy is removed all we have to do // is to refresh the compilation unit if (isWorkingCopy(element)) { refreshWorkingCopy((IWorkingCopy)element); return; } Object parent= internalGetParent(element); postRemove(element); if (parent instanceof IPackageFragment) postUpdateIcon((IPackageFragment)parent); // we are filtering out empty subpackages, so we // a package becomes empty we remove it from the viewer. if (isPackageFragmentEmpty(element.getParent())) { if (fViewer.testFindItem(parent) != null) postRefresh(internalGetParent(parent)); } return; } if (kind == IJavaElementDelta.ADDED) { // when a working copy is added all we have to do // is to refresh the compilation unit if (isWorkingCopy(element)) { refreshWorkingCopy((IWorkingCopy)element); return; } Object parent= internalGetParent(element); // we are filtering out empty subpackages, so we // have to handle additions to them specially. if (parent instanceof IPackageFragment) { Object grandparent= internalGetParent(parent); // 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View // avoid posting a refresh to an unvisible parent if (parent.equals(fInput)) { postRefresh(parent); } else { // refresh from grandparent if parent isn't visible yet if (fViewer.testFindItem(parent) == null) postRefresh(grandparent); else { postRefresh(parent); } } } else { postAdd(parent, element); } } if (element instanceof ICompilationUnit) { if (getProvideWorkingCopy()) { IJavaElement original= ((IWorkingCopy)element).getOriginalElement(); if (original != null) element= original; } if (kind == IJavaElementDelta.CHANGED) { postRefresh(element); updateSelection(delta); return; } } // we don't show the contents of a compilation or IClassFile, so don't go any deeper if ((element instanceof ICompilationUnit) || (element instanceof IClassFile)) return; // the contents of an external JAR has changed if (element instanceof IPackageFragmentRoot && ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0)) postRefresh(element); // the source attachment of a JAR has changed if (element instanceof IPackageFragmentRoot && (((flags & IJavaElementDelta.F_SOURCEATTACHED) != 0 || ((flags & IJavaElementDelta.F_SOURCEDETACHED)) != 0))) postUpdateIcon(element); if (isClassPathChange(delta)) { // throw the towel and do a full refresh of the affected java project. postRefresh(element.getJavaProject()); } if (delta.getResourceDeltas() != null) { IResourceDelta[] rd= delta.getResourceDeltas(); for (int i= 0; i < rd.length; i++) { processResourceDelta(rd[i], element); } } handleAffectedChildren(delta, element); } private void handleAffectedChildren(IJavaElementDelta delta, IJavaElement element) throws JavaModelException { IJavaElementDelta[] affectedChildren= delta.getAffectedChildren(); if (affectedChildren.length > 1) { // a package fragment might become non empty refresh from the parent if (element instanceof IPackageFragment) { IJavaElement parent= (IJavaElement)internalGetParent(element); // 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View // avoid posting a refresh to an unvisible parent if (element.equals(fInput)) { postRefresh(element); } else { postRefresh(parent); } return; } // more than one child changed, refresh from here downwards if (element instanceof IPackageFragmentRoot) postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element)); else postRefresh(element); return; } processAffectedChildren(affectedChildren); } protected void processAffectedChildren(IJavaElementDelta[] affectedChildren) throws JavaModelException { for (int i= 0; i < affectedChildren.length; i++) { processDelta(affectedChildren[i]); } } private boolean isOnClassPath(ICompilationUnit element) throws JavaModelException { IJavaProject project= element.getJavaProject(); if (project == null || !project.exists()) return false; return project.isOnClasspath(element); } /** * Updates the selection. It finds newly added elements * and selects them. */ private void updateSelection(IJavaElementDelta delta) { final IJavaElement addedElement= findAddedElement(delta); if (addedElement != null) { final StructuredSelection selection= new StructuredSelection(addedElement); postRunnable(new Runnable() { public void run() { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { // 19431 // if the item is already visible then select it if (fViewer.testFindItem(addedElement) != null) fViewer.setSelection(selection); } } }); } } private IJavaElement findAddedElement(IJavaElementDelta delta) { if (delta.getKind() == IJavaElementDelta.ADDED) return delta.getElement(); IJavaElementDelta[] affectedChildren= delta.getAffectedChildren(); for (int i= 0; i < affectedChildren.length; i++) return findAddedElement(affectedChildren[i]); return null; } /** * Refreshes the Compilation unit corresponding to the workging copy * @param iWorkingCopy */ private void refreshWorkingCopy(IWorkingCopy workingCopy) { IJavaElement original= workingCopy.getOriginalElement(); if (original != null) postRefresh(original); } private boolean isWorkingCopy(IJavaElement element) { return (element instanceof IWorkingCopy) && ((IWorkingCopy)element).isWorkingCopy(); } /** * Updates the package icon */ private void postUpdateIcon(final IJavaElement element) { postRunnable(new Runnable() { public void run() { // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE}); } }); } /** * Process resource deltas */ private void processResourceDelta(IResourceDelta delta, Object parent) { int status= delta.getKind(); IResource resource= delta.getResource(); // filter out changes affecting the output folder if (resource == null) return; // this could be optimized by handling all the added children in the parent if ((status & IResourceDelta.REMOVED) != 0) { if (parent instanceof IPackageFragment) // refresh one level above to deal with empty package filtering properly postRefresh(internalGetParent(parent)); else postRemove(resource); } if ((status & IResourceDelta.ADDED) != 0) { if (parent instanceof IPackageFragment) // refresh one level above to deal with empty package filtering properly postRefresh(internalGetParent(parent)); else postAdd(parent, resource); } IResourceDelta[] affectedChildren= delta.getAffectedChildren(); if (affectedChildren.length > 1) { // more than one child changed, refresh from here downwards postRefresh(resource); return; } for (int i= 0; i < affectedChildren.length; i++) processResourceDelta(affectedChildren[i], resource); } private void postRefresh(final Object root) { postRunnable(new Runnable() { public void run() { // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()){ ctrl.setRedraw(false); fViewer.refresh(root); ctrl.setRedraw(true); } } }); } private void postAdd(final Object parent, final Object element) { postRunnable(new Runnable() { public void run() { // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()){ ctrl.setRedraw(false); fViewer.add(parent, element); ctrl.setRedraw(true); } } }); } private void postRemove(final Object element) { postRunnable(new Runnable() { public void run() { // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.setRedraw(false); fViewer.remove(element); ctrl.setRedraw(true); } } }); } private void postRunnable(final Runnable r) { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.getDisplay().asyncExec(r); } } void setIsFlatLayout(boolean state) { fIsFlatLayout= state; } }
25,827
Bug 25827 Disposing of MemberFilterActionGroup
Build 2.0.2 and 2.1 When investigating an editor memory leak PR we found out that this group has a dispose method which is never called. When we then called from the editor it throw an exeption (viewer was disposed). Don't know if the group really needs dispose() if so it should get called.
resolved fixed
4534791
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T09:46:11Z
2002-11-07T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/MembersView.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; public class MembersView extends JavaBrowsingPart implements IPropertyChangeListener { private MemberFilterActionGroup fMemberFilterActionGroup; public MembersView() { setHasWorkingSetFilter(false); setHasCustomSetFilter(true); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); } /** * Creates and returns the label provider for this part. * * @return the label provider * @see ILabelProvider */ protected ILabelProvider createLabelProvider() { return new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS, AppearanceAwareLabelProvider.getDecorators(true, new OverrideIndicatorLabelDecorator(null)) ); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ protected String getHelpContextId() { return IJavaHelpContextIds.MEMBERS_VIEW; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { ProblemTreeViewer viewer= new ProblemTreeViewer(parent, SWT.MULTI); fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaUI.ID_MEMBERS_VIEW); return viewer; } protected void fillToolBar(IToolBarManager tbm) { tbm.add(new LexicalSortingAction(getViewer(), JavaUI.ID_MEMBERS_VIEW)); fMemberFilterActionGroup.contributeToToolBar(tbm); } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ protected boolean isValidInput(Object element) { if (element instanceof IType) { IType type= (IType)element; return type.isBinary() || type.getDeclaringType() == null; } return false; } /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element instanceof IMember) return super.isValidElement(((IMember)element).getDeclaringType()); else if (element instanceof IImportDeclaration) return isValidElement(((IJavaElement)element).getParent()); else if (element instanceof IImportContainer) { Object input= getViewer().getInput(); if (input instanceof IJavaElement) { ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT); return cu.equals(importContainerCu); } else { IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE); IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE); return cf != null && cf.equals(importContainerCf); } } } return false; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ protected IJavaElement findElementToSelect(IJavaElement je) { if (je == null) return null; switch (je.getElementType()) { case IJavaElement.TYPE: if (((IType)je).getDeclaringType() == null) return null; // fall through case IJavaElement.METHOD: // fall through case IJavaElement.FIELD: // fall through case IJavaElement.PACKAGE_DECLARATION: // fall through case IJavaElement.IMPORT_CONTAINER: return getSuitableJavaElement(je); case IJavaElement.IMPORT_DECLARATION: je= getSuitableJavaElement(je); if (je != null) { ICompilationUnit cu= (ICompilationUnit)je.getParent().getParent(); try { if (cu.getImports()[0].equals(je)) { Object selectedElement= getSingleElementFromSelection(getViewer().getSelection()); if (selectedElement instanceof IImportContainer) return (IImportContainer)selectedElement; } } catch (JavaModelException ex) { // return je; } return je; } break; } return null; } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; switch (je.getElementType()) { case IJavaElement.TYPE: IType type= ((IType)je).getDeclaringType(); if (type == null) return je; else return findInputForJavaElement(type); case IJavaElement.COMPILATION_UNIT: return getTypeForCU((ICompilationUnit)je); case IJavaElement.CLASS_FILE: try { return findInputForJavaElement(((IClassFile)je).getType()); } catch (JavaModelException ex) { return null; } case IJavaElement.IMPORT_DECLARATION: return findInputForJavaElement(je.getParent()); case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: IJavaElement parent= je.getParent(); if (parent instanceof ICompilationUnit) { IType[] types; try { types= ((ICompilationUnit)parent).getAllTypes(); } catch (JavaModelException ex) { return null; } if (types.length > 0) return types[0]; else return null; } else if (parent instanceof IClassFile) return findInputForJavaElement(parent); default: if (je instanceof IMember) return findInputForJavaElement(((IMember)je).getDeclaringType()); } return null; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { super.saveState(memento); fMemberFilterActionGroup.saveState(memento); } protected void restoreState(IMemento memento) { super.restoreState(memento); fMemberFilterActionGroup.restoreState(memento); getViewer().getControl().setRedraw(false); getViewer().refresh(); getViewer().getControl().setRedraw(true); } protected void hookViewerListeners() { super.hookViewerListeners(); getViewer().addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { TreeViewer viewer= (TreeViewer)getViewer(); Object element= ((IStructuredSelection)event.getSelection()).getFirstElement(); if (viewer.isExpandable(element)) viewer.setExpandedState(element, !viewer.getExpandedState(element)); } }); } boolean isInputAWorkingCopy() { Object input= getViewer().getInput(); if (input instanceof IJavaElement) { ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) return cu.isWorkingCopy(); } return false; } protected void restoreSelection() { IEditorPart editor= getViewSite().getPage().getActiveEditor(); if (editor != null) setSelectionFromEditor(editor); } /* (non-Javadoc) * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(MembersOrderPreferencePage.PREF_OUTLINE_SORT_OPTION)) { getViewer().refresh(); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#dispose() */ public void dispose() { super.dispose(); JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); } }
25,827
Bug 25827 Disposing of MemberFilterActionGroup
Build 2.0.2 and 2.1 When investigating an editor memory leak PR we found out that this group has a dispose method which is never called. When we then called from the editor it throw an exeption (viewer was disposed). Don't know if the group really needs dispose() if so it should get called.
resolved fixed
4534791
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T09:46:11Z
2002-11-07T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
package org.eclipse.jdt.internal.ui.javaeditor; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProviderChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.IActionBars; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.internal.model.WorkbenchAdapter; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.jdt.core.ElementChangedEvent; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IElementChangedListener; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator; import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.JdtActionConstants; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * The content outline page of the Java editor. The viewer implements a proprietary * update mechanism based on Java model deltas. It does not react on domain changes. * It is specified to show the content of ICompilationUnits and IClassFiles. * Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>. */ class JavaOutlinePage extends Page implements IContentOutlinePage { static Object[] NO_CHILDREN= new Object[0]; /** * The element change listener of the java outline viewer. * @see IElementChangedListener */ class ElementChangedListener implements IElementChangedListener { public void elementChanged(final ElementChangedEvent e) { if (getControl() == null) return; Display d= getControl().getDisplay(); if (d != null) { d.asyncExec(new Runnable() { public void run() { ICompilationUnit cu= (ICompilationUnit) fInput; IJavaElement base= cu; if (fTopLevelTypeOnly) { base= getMainType(cu); if (base == null) { if (fOutlineViewer != null) fOutlineViewer.refresh(); return; } } IJavaElementDelta delta= findElement(base, e.getDelta()); if (delta != null && fOutlineViewer != null) { fOutlineViewer.reconcile(delta); } } }); } } protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) { if (delta == null || unit == null) return null; IJavaElement element= delta.getElement(); if (unit.equals(element)) return delta; if (element.getElementType() > IJavaElement.CLASS_FILE) return null; IJavaElementDelta[] children= delta.getAffectedChildren(); if (children == null || children.length == 0) return null; for (int i= 0; i < children.length; i++) { IJavaElementDelta d= findElement(unit, children[i]); if (d != null) return d; } return null; } }; static class NoClassElement extends WorkbenchAdapter implements IAdaptable { /* * @see java.lang.Object#toString() */ public String toString() { return JavaEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$ } /* * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) */ public Object getAdapter(Class clas) { if (clas == IWorkbenchAdapter.class) return this; return null; } } /** * Content provider for the children of an ICompilationUnit or * an IClassFile * @see ITreeContentProvider */ class ChildrenProvider implements ITreeContentProvider { private Object[] NO_CLASS= new Object[] {new NoClassElement()}; private ElementChangedListener fListener; protected boolean matches(IJavaElement element) { if (element.getElementType() == IJavaElement.METHOD) { String name= element.getElementName(); return (name != null && name.indexOf('<') >= 0); } return false; } protected IJavaElement[] filter(IJavaElement[] children) { boolean initializers= false; for (int i= 0; i < children.length; i++) { if (matches(children[i])) { initializers= true; break; } } if (!initializers) return children; Vector v= new Vector(); for (int i= 0; i < children.length; i++) { if (matches(children[i])) continue; v.addElement(children[i]); } IJavaElement[] result= new IJavaElement[v.size()]; v.copyInto(result); return result; } public Object[] getChildren(Object parent) { if (parent instanceof IParent) { IParent c= (IParent) parent; try { return filter(c.getChildren()); } catch (JavaModelException x) { JavaPlugin.log(x); } } return NO_CHILDREN; } public Object[] getElements(Object parent) { if (fTopLevelTypeOnly) { if (parent instanceof ICompilationUnit) { try { IType type= getMainType((ICompilationUnit) parent); return type != null ? type.getChildren() : NO_CLASS; } catch (JavaModelException e) { JavaPlugin.log(e); } } else if (parent instanceof IClassFile) { try { IType type= getMainType((IClassFile) parent); return type != null ? type.getChildren() : NO_CLASS; } catch (JavaModelException e) { JavaPlugin.log(e); } } } return getChildren(parent); } public Object getParent(Object child) { if (child instanceof IJavaElement) { IJavaElement e= (IJavaElement) child; return e.getParent(); } return null; } public boolean hasChildren(Object parent) { if (parent instanceof IParent) { IParent c= (IParent) parent; try { IJavaElement[] children= filter(c.getChildren()); return (children != null && children.length > 0); } catch (JavaModelException x) { JavaPlugin.log(x); } } return false; } public boolean isDeleted(Object o) { return false; } public void dispose() { if (fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; } } /* * @see IContentProvider#inputChanged(Viewer, Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { boolean isCU= (newInput instanceof ICompilationUnit); if (isCU && fListener == null) { fListener= new ElementChangedListener(); JavaCore.addElementChangedListener(fListener); } else if (!isCU && fListener != null) { JavaCore.removeElementChangedListener(fListener); fListener= null; } } }; class JavaOutlineViewer extends TreeViewer { /** * Indicates an item which has been reused. At the point of * its reuse it has been expanded. This field is used to * communicate between <code>internalExpandToLevel</code> and * <code>reuseTreeItem</code>. */ private Item fReusedExpandedItem; 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) { if (fTopLevelTypeOnly && delta.getElement() instanceof IType && (delta.getKind() & IJavaElementDelta.ADDED) != 0) { refresh(); } else { Widget w= findItem(fInput); if (w != null && !w.isDisposed()) 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; } protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) { if (element instanceof IMethod) { if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { try { return ((IMethod)element).isMainMethod(); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } return "main".equals(element.getElementName()); //$NON-NLS-1$ } return false; } protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException { if (element instanceof IMember && !(element instanceof IInitializer)) return ((IMember) element).getNameRange(); if (element instanceof ISourceReference) return ((ISourceReference) element).getSourceRange(); return null; } protected boolean overlaps(ISourceRange range, int start, int end) { return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end; } protected boolean filtered(IJavaElement parent, IJavaElement child) { Object[] result= new Object[] { child }; ViewerFilter[] filters= getFilters(); for (int i= 0; i < filters.length; i++) { result= filters[i].filter(this, parent, result); if (result.length == 0) return true; } return false; } protected void update(Widget w, IJavaElementDelta delta) { Item item; IJavaElement parent= delta.getElement(); IJavaElementDelta[] affected= delta.getAffectedChildren(); Item[] children= getChildren(w); boolean doUpdateParent= false; Vector deletions= new Vector(); Vector additions= new Vector(); for (int i= 0; i < affected.length; i++) { IJavaElementDelta affectedDelta= affected[i]; IJavaElement affectedElement= affectedDelta.getElement(); int status= affected[i].getKind(); // find tree item with affected element int j; for (j= 0; j < children.length; j++) if (affectedElement.equals(children[j].getData())) break; if (j == children.length) { // addition if ((status & IJavaElementDelta.CHANGED) != 0 && (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 && !filtered(parent, affectedElement)) { additions.addElement(affectedDelta); } continue; } item= children[j]; // removed if ((status & IJavaElementDelta.REMOVED) != 0) { deletions.addElement(item); doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); // changed } else if ((status & IJavaElementDelta.CHANGED) != 0) { int change= affectedDelta.getFlags(); doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { if (filtered(parent, affectedElement)) deletions.addElement(item); else updateItem(item, affectedElement); } if ((change & IJavaElementDelta.F_CONTENT) != 0) updateItem(item, affectedElement); if ((change & IJavaElementDelta.F_CHILDREN) != 0) update(item, affectedDelta); } } // find all elements to add IJavaElementDelta[] add= delta.getAddedChildren(); if (additions.size() > 0) { IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()]; System.arraycopy(add, 0, tmp, 0, add.length); for (int i= 0; i < additions.size(); i++) tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i); add= tmp; } // add at the right position go2: for (int i= 0; i < add.length; i++) { try { IJavaElement e= add[i].getElement(); if (filtered(parent, e)) continue go2; doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e); ISourceRange rng= getSourceRange(e); int start= rng.getOffset(); int end= start + rng.getLength() - 1; Item last= null; item= null; children= getChildren(w); for (int j= 0; j < children.length; j++) { item= children[j]; IJavaElement r= (IJavaElement) item.getData(); if (r == null) { // parent node collapsed and not be opened before -> do nothing continue go2; } try { rng= getSourceRange(r); if (overlaps(rng, start, end)) { // be tolerant if the delta is not correct, or if // the tree has been updated other than by a delta reuseTreeItem(item, e); continue go2; } else if (rng.getOffset() > start) { if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, (Object) e); } else { // nothing to reuse createTreeItem(w, (Object) e, j); } continue go2; } } catch (JavaModelException x) { // stumbled over deleted element } last= item; } // add at the end of the list if (last != null && deletions.contains(last)) { // reuse item deletions.removeElement(last); reuseTreeItem(last, e); } else { // nothing to reuse createTreeItem(w, e, -1); } } catch (JavaModelException x) { // the element to be added is not present -> don't add it } } // remove items which haven't been reused Enumeration e= deletions.elements(); while (e.hasMoreElements()) { item= (Item) e.nextElement(); disassociate(item); item.dispose(); } if (doUpdateParent) updateItem(w, delta.getElement()); } /* * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) */ protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { Object input= getInput(); if (event instanceof ProblemsLabelChangedEvent) { ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; if (e.isMarkerChange() && input instanceof ICompilationUnit) { return; // marker changes can be ignored } } // look if the underlying resource changed Object[] changed= event.getElements(); if (changed != null) { IResource resource= getUnderlyingResource(); if (resource != null) { for (int i= 0; i < changed.length; i++) { if (changed[i].equals(resource)) { // change event to a full refresh event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource()); break; } } } } super.handleLabelProviderChanged(event); } private IResource getUnderlyingResource() { Object input= getInput(); if (input instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit) input; if (cu.isWorkingCopy()) { return cu.getOriginalElement().getResource(); } else { return cu.getResource(); } } else if (input instanceof IClassFile) { return ((IClassFile) input).getResource(); } return null; } }; class LexicalSortingAction extends Action { private JavaElementSorter fSorter= new JavaElementSorter(); public LexicalSortingAction() { super(); WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$ valueChanged(checked, false); } public void run() { valueChanged(isChecked(), true); } private void valueChanged(final boolean on, boolean store) { setChecked(on); BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() { public void run() { fOutlineViewer.setSorter(on ? fSorter : null); } }); if (store) JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$ } }; class ClassOnlyAction extends Action { public ClassOnlyAction() { super(); setText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$ setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$ setDescription(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "class_obj.gif"); //$NON-NLS-1$ IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore(); boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$ setTopLevelTypeOnly(showclass); } /* * @see org.eclipse.jface.action.Action#run() */ public void run() { setTopLevelTypeOnly(!fTopLevelTypeOnly); } private void setTopLevelTypeOnly(boolean show) { fTopLevelTypeOnly= show; setChecked(show); fOutlineViewer.refresh(); IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore(); preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$ } }; /** A flag to show contents of top level type only */ private boolean fTopLevelTypeOnly; private IJavaElement fInput; private String fContextMenuID; private Menu fMenu; private JavaOutlineViewer fOutlineViewer; private JavaEditor fEditor; private MemberFilterActionGroup fMemberFilterActionGroup; private ListenerList fSelectionChangedListeners= new ListenerList(); private Hashtable fActions= new Hashtable(); private TogglePresentationAction fTogglePresentation; private ToggleTextHoverAction fToggleTextHover; private GotoErrorAction fPreviousError; private GotoErrorAction fNextError; private TextEditorAction fShowJavadoc; private TextOperationAction fUndo; private TextOperationAction fRedo; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; private IPropertyChangeListener fPropertyChangeListener; public JavaOutlinePage(String contextMenuID, JavaEditor editor) { super(); Assert.isNotNull(editor); fContextMenuID= contextMenuID; fEditor= editor; fTogglePresentation= new TogglePresentationAction(); fToggleTextHover= new ToggleTextHoverAction(); fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$ fPreviousError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR); fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$ fNextError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR); fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO); fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO); fTogglePresentation.setEditor(editor); fToggleTextHover.setEditor(editor); fPreviousError.setEditor(editor); fNextError.setEditor(editor); fPropertyChangeListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doPropertyChange(event); } }; JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); } /** * Returns the primary type of a compilation unit (has the same * name as the compilation unit). * * @param compilationUnit the compilation unit * @return returns the primary type of the compilation unit, or * <code>null</code> if is does not have one */ protected IType getMainType(ICompilationUnit compilationUnit) { String name= compilationUnit.getElementName(); int index= name.indexOf('.'); if (index != -1) name= name.substring(0, index); IType type= compilationUnit.getType(name); return type.exists() ? type : null; } /** * Returns the primary type of a class file. * * @param classFile the class file * @return returns the primary type of the class file, or <code>null</code> * if is does not have one */ protected IType getMainType(IClassFile classFile) { try { IType type= classFile.getType(); return type.exists() ? type : null; } catch (JavaModelException e) { return null; } } /* (non-Javadoc) * Method declared on Page */ public void init(IPageSite pageSite) { super.init(pageSite); } private void doPropertyChange(PropertyChangeEvent event) { if (fOutlineViewer != null) { if (MembersOrderPreferencePage.PREF_OUTLINE_SORT_OPTION.equals(event.getProperty())) { fOutlineViewer.refresh(); } } } /* * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) */ public void addSelectionChangedListener(ISelectionChangedListener listener) { if (fOutlineViewer != null) fOutlineViewer.addSelectionChangedListener(listener); else fSelectionChangedListeners.add(listener); } /* * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { if (fOutlineViewer != null) fOutlineViewer.removeSelectionChangedListener(listener); else fSelectionChangedListeners.remove(listener); } /* * @see ISelectionProvider#setSelection(ISelection) */ public void setSelection(ISelection selection) { if (fOutlineViewer != null) fOutlineViewer.setSelection(selection); } /* * @see ISelectionProvider#getSelection() */ public ISelection getSelection() { if (fOutlineViewer == null) return StructuredSelection.EMPTY; return fOutlineViewer.getSelection(); } private void registerToolbarActions() { IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager(); if (toolBarManager != null) { toolBarManager.add(new ClassOnlyAction()); toolBarManager.add(new LexicalSortingAction()); fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$ fMemberFilterActionGroup.contributeToToolBar(toolBarManager); } } /* * @see IPage#createControl */ public void createControl(Composite parent) { Tree tree= new Tree(parent, SWT.MULTI); ILabelProvider lprovider= new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS, AppearanceAwareLabelProvider.getDecorators(true, new OverrideIndicatorLabelDecorator(null)) ); fOutlineViewer= new JavaOutlineViewer(tree); fOutlineViewer.setContentProvider(new ChildrenProvider()); fOutlineViewer.setLabelProvider(new DecoratingLabelProvider(lprovider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); Object[] listeners= fSelectionChangedListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { fSelectionChangedListeners.remove(listeners[i]); fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]); } MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { contextMenuAboutToShow(manager); } }); fMenu= manager.createContextMenu(tree); tree.setMenu(fMenu); IPageSite site= getSite(); site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ site.setSelectionProvider(fOutlineViewer); // we must create the groups after we have set the selection provider to the site fActionGroups= new CompositeActionGroup(new ActionGroup[] { new OpenViewActionGroup(this), new ShowActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new GenerateActionGroup(this), new JavaSearchActionGroup(this)}); // register global actions IActionBars bars= site.getActionBars(); bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo); bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo); bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError); bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError); bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc); bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation); bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_TEXT_HOVER, fToggleTextHover); // http://dev.eclipse.org/bugs/show_bug.cgi?id=18968 bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError); bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError); fActionGroups.fillActionBars(bars); IStatusLineManager statusLineManager= site.getActionBars().getStatusLineManager(); if (statusLineManager != null) { StatusBarUpdater updater= new StatusBarUpdater(statusLineManager); fOutlineViewer.addSelectionChangedListener(updater); } registerToolbarActions(); fOutlineViewer.setInput(fInput); fOutlineViewer.getControl().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { handleKeyReleased(e); } }); initDragAndDrop(); } public void dispose() { if (fEditor == null) return; fEditor.outlinePageClosed(); fEditor= null; fSelectionChangedListeners.clear(); fSelectionChangedListeners= null; if (fPropertyChangeListener != null) { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fMenu != null && !fMenu.isDisposed()) { fMenu.dispose(); fMenu= null; } if (fActionGroups != null) fActionGroups.dispose(); fTogglePresentation.setEditor(null); fToggleTextHover.setEditor(null); fPreviousError.setEditor(null); fNextError.setEditor(null); fOutlineViewer= null; super.dispose(); } public Control getControl() { if (fOutlineViewer != null) return fOutlineViewer.getControl(); return null; } public void setInput(IJavaElement inputElement) { fInput= inputElement; if (fOutlineViewer != null) fOutlineViewer.setInput(fInput); } public void select(ISourceReference reference) { if (fOutlineViewer != null) { ISelection s= fOutlineViewer.getSelection(); if (s instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection) s; List elements= ss.toList(); if (!elements.contains(reference)) { s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference)); fOutlineViewer.setSelection(s, true); } } } } public void setAction(String actionID, IAction action) { Assert.isNotNull(actionID); if (action == null) fActions.remove(actionID); else fActions.put(actionID, action); } public IAction getAction(String actionID) { Assert.isNotNull(actionID); return (IAction) fActions.get(actionID); } /** * Convenience method to add the action installed under the given actionID to the * specified group of the menu. */ protected void addAction(IMenuManager menu, String group, String actionID) { IAction action= getAction(actionID); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (action.isEnabled()) { IMenuManager subMenu= menu.findMenuUsingPath(group); if (subMenu != null) subMenu.add(action); else menu.appendToGroup(group, action); } } } protected void contextMenuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); IStructuredSelection selection= (IStructuredSelection)getSelection(); fActionGroups.setContext(new ActionContext(selection)); fActionGroups.fillContextMenu(menu); } /* * @see Page#setFocus() */ public void setFocus() { if (fOutlineViewer != null) fOutlineViewer.getControl().setFocus(); } /** * Checkes whether a given Java element is an inner type. */ private boolean isInnerType(IJavaElement element) { if (element.getElementType() == IJavaElement.TYPE) { IJavaElement parent= element.getParent(); int type= parent.getElementType(); return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE); } return false; } /** * Handles key events in viewer. */ private void handleKeyReleased(KeyEvent event) { if (event.stateMask != 0) return; IAction action= null; if (event.character == SWT.DEL) { action= fCCPActionGroup.getDeleteAction(); } if (action != null && action.isEnabled()) action.run(); } private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fOutlineViewer) }; fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); // Drag Adapter Control control= fOutlineViewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fOutlineViewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners)); }}
25,827
Bug 25827 Disposing of MemberFilterActionGroup
Build 2.0.2 and 2.1 When investigating an editor memory leak PR we found out that this group has a dispose method which is never called. When we then called from the editor it throw an exeption (viewer was disposed). Don't know if the group really needs dispose() if so it should get called.
resolved fixed
4534791
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T09:46:11Z
2002-11-07T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.OpenStrategy; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetManager; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.MoveResourceAction; import org.eclipse.ui.actions.OpenInNewWindowAction; import org.eclipse.ui.actions.RenameResourceAction; import org.eclipse.ui.views.framelist.BackAction; import org.eclipse.ui.views.framelist.ForwardAction; import org.eclipse.ui.views.framelist.FrameList; import org.eclipse.ui.views.framelist.GoIntoAction; import org.eclipse.ui.views.framelist.UpAction; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IOpenable; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.actions.BuildActionGroup; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.ImportActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.JdtActionConstants; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.ui.actions.NavigateActionGroup; import org.eclipse.jdt.ui.actions.ProjectActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.preferences.AppearancePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup; class PackageExplorerActionGroup extends CompositeActionGroup implements ISelectionChangedListener { private PackageExplorerPart fPart; private GoIntoAction fZoomInAction; private BackAction fBackAction; private ForwardAction fForwardAction; private UpAction fUpAction; private GotoTypeAction fGotoTypeAction; private GotoPackageAction fGotoPackageAction; private CollapseAllAction fCollapseAllAction; private RenameResourceAction fRenameResourceAction; private MoveResourceAction fMoveResourceAction; private NavigateActionGroup fNavigateActionGroup; private BuildActionGroup fBuildActionGroup; private CCPActionGroup fCCPActionGroup; private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup; private MemberFilterActionGroup fMemberFilterActionGroup; private CustomFiltersActionGroup fCustomFiltersActionGroup; public PackageExplorerActionGroup(PackageExplorerPart part) { super(); fPart= part; IWorkbenchPartSite site = fPart.getSite(); Shell shell= site.getShell(); ISelectionProvider provider= site.getSelectionProvider(); IStructuredSelection selection= (IStructuredSelection) provider.getSelection(); setGroups(new ActionGroup[] { new NewWizardsActionGroup(site), fNavigateActionGroup= new NavigateActionGroup(fPart), new ShowActionGroup(fPart), fCCPActionGroup= new CCPActionGroup(fPart), new RefactorActionGroup(fPart), new ImportActionGroup(fPart), new GenerateActionGroup(fPart), fBuildActionGroup= new BuildActionGroup(fPart), new JavaSearchActionGroup(fPart), new ProjectActionGroup(fPart), fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(part.getViewer(), JavaUI.ID_PACKAGES, shell, createTitleUpdater()), new LayoutActionGroup(part)}); PackagesFrameSource frameSource= new PackagesFrameSource(fPart); FrameList frameList= new FrameList(frameSource); frameSource.connectTo(frameList); fZoomInAction= new GoIntoAction(frameList); fBackAction= new BackAction(frameList); fForwardAction= new ForwardAction(frameList); fUpAction= new UpAction(frameList); fRenameResourceAction= new RenameResourceAction(shell); fMoveResourceAction= new MoveResourceAction(shell); fGotoTypeAction= new GotoTypeAction(fPart); fGotoPackageAction= new GotoPackageAction(fPart); fCollapseAllAction= new CollapseAllAction(fPart); fMemberFilterActionGroup= new MemberFilterActionGroup(fPart.getViewer(), "PackageView"); //$NON-NLS-1$ fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, fPart.getViewer()); provider.addSelectionChangedListener(this); update(selection); } public void dispose() { ISelectionProvider provider= fPart.getSite().getSelectionProvider(); provider.removeSelectionChangedListener(this); super.dispose(); } //---- Selection changed listener --------------------------------------------------------- public void selectionChanged(SelectionChangedEvent event) { fRenameResourceAction.selectionChanged(event); fMoveResourceAction.selectionChanged(event); IStructuredSelection selection= (IStructuredSelection)event.getSelection(); update(selection); } private void update(IStructuredSelection selection) { int size= selection.size(); Object element= selection.getFirstElement(); IActionBars actionBars= fPart.getViewSite().getActionBars(); if (size == 1 && element instanceof IResource) { actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, fRenameResourceAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, fMoveResourceAction); } else { actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, null); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, null); } actionBars.updateActionBars(); } //---- Persistent state ----------------------------------------------------------------------- /* package */ void restoreState(IMemento memento) { fMemberFilterActionGroup.restoreState(memento); fWorkingSetFilterActionGroup.restoreState(memento); fCustomFiltersActionGroup.restoreState(memento); fPart.getViewer().getControl().setRedraw(false); fPart.getViewer().refresh(); fPart.getViewer().getControl().setRedraw(true); } /* package */ void saveState(IMemento memento) { fMemberFilterActionGroup.saveState(memento); fWorkingSetFilterActionGroup.saveState(memento); fCustomFiltersActionGroup.saveState(memento); } //---- Action Bars ---------------------------------------------------------------------------- public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); setGlobalActionHandlers(actionBars); fillToolBar(actionBars.getToolBarManager()); fillViewMenu(actionBars.getMenuManager()); fCustomFiltersActionGroup.fillActionBars(actionBars); } private void setGlobalActionHandlers(IActionBars actionBars) { // Navigate Go Into and Go To actions. actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BACK, fBackAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.FORWARD, fForwardAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction); } /* package */ void fillToolBar(IToolBarManager toolBar) { toolBar.removeAll(); toolBar.add(fBackAction); toolBar.add(fForwardAction); toolBar.add(fUpAction); if (AppearancePreferencePage.showCompilationUnitChildren()) { toolBar.add(new Separator()); fMemberFilterActionGroup.contributeToToolBar(toolBar); } toolBar.add(new Separator()); toolBar.add(fCollapseAllAction); } /* package */ void fillViewMenu(IMenuManager menu) { menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$ } /* package */ void handleSelectionChanged(SelectionChangedEvent event) { fZoomInAction.update(); } //---- Context menu ------------------------------------------------------------------------- public void fillContextMenu(IMenuManager menu) { IStructuredSelection selection= (IStructuredSelection)getContext().getSelection(); int size= selection.size(); Object element= selection.getFirstElement(); addGotoMenu(menu, element, size); addOpenNewWindowAction(menu, element); super.fillContextMenu(menu); } private void addGotoMenu(IMenuManager menu, Object element, int size) { if (size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer)) menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction); } private boolean isNewTarget(IJavaElement element) { if (element == null) return false; int type= element.getElementType(); return type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.COMPILATION_UNIT || type == IJavaElement.TYPE; } private boolean isGoIntoTarget(Object element) { if (element == null) return false; if (element instanceof IJavaElement) { int type= ((IJavaElement)element).getElementType(); return type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT; } return false; } private void addOpenNewWindowAction(IMenuManager menu, Object element) { if (element instanceof IJavaElement) { element= ((IJavaElement)element).getResource(); } if (!(element instanceof IContainer)) return; menu.appendToGroup( IContextMenuConstants.GROUP_OPEN, new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element)); } //---- Key board and mouse handling ------------------------------------------------------------ /* package*/ void handleDoubleClick(DoubleClickEvent event) { TreeViewer viewer= fPart.getViewer(); Object element= ((IStructuredSelection)event.getSelection()).getFirstElement(); if (viewer.isExpandable(element)) { if (JavaBasePreferencePage.doubleClickGoesInto()) { // don't zoom into compilation units and class files if (element instanceof IOpenable && !(element instanceof ICompilationUnit) && !(element instanceof IClassFile)) { fZoomInAction.run(); } } else { if (element instanceof ICompilationUnit && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK) return; viewer.setExpandedState(element, !viewer.getExpandedState(element)); } } } /* package */ void handleOpen(OpenEvent event) { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled()) { openAction.run(); return; } } /* package */ void handleKeyEvent(KeyEvent event) { if (event.stateMask != 0) return; if (event.keyCode == SWT.F5) { IAction refreshAction= fBuildActionGroup.getRefreshAction(); if (refreshAction != null && refreshAction.isEnabled()) refreshAction.run(); } else if (event.character == SWT.DEL) { IAction delete= fCCPActionGroup.getDeleteAction(); if (delete != null && delete.isEnabled()) delete.run(); } else if (event.keyCode == SWT.BS) { if (fUpAction != null && fUpAction.isEnabled()) fUpAction.run(); } } private IPropertyChangeListener createTitleUpdater() { return new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property= event.getProperty(); if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) { IWorkingSet workingSet= (IWorkingSet)event.getNewValue(); String workingSetName= null; if (workingSet != null) workingSetName= workingSet.getName(); fPart.setWorkingSetName(workingSetName); fPart.updateTitle(); } } }; } }
25,827
Bug 25827 Disposing of MemberFilterActionGroup
Build 2.0.2 and 2.1 When investigating an editor memory leak PR we found out that this group has a dispose method which is never called. When we then called from the editor it throw an exeption (viewer was disposed). Don't know if the group really needs dispose() if so it should get called.
resolved fixed
4534791
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T09:46:11Z
2002-11-07T14:40:00Z
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.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Table; 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.DecoratingLabelProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IMemento; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PlatformUI; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.util.SelectionUtil; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.ui.actions.OpenAction; /** * 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 ProblemTableViewer { private static final String TAG_SHOWINHERITED= "showinherited"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "mv_vertical_scroll"; //$NON-NLS-1$ private static final int LABEL_BASEFLAGS= AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS; private JavaUILabelProvider fLabelProvider; private MemberFilterActionGroup fMemberFilterActionGroup; private OpenAction fOpen; private ShowInheritedMembersAction fShowInheritedMembersAction; public MethodsViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { super(new Table(parent, SWT.MULTI)); fLabelProvider= new HierarchyLabelProvider(lifeCycle); setLabelProvider(new DecoratingLabelProvider(fLabelProvider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); setContentProvider(new MethodsContentProvider(lifeCycle)); fOpen= new OpenAction(part.getSite()); addOpenListener(new IOpenListener() { public void open(OpenEvent event) { fOpen.run(); } }); fMemberFilterActionGroup= new MemberFilterActionGroup(this, "HierarchyMethodView"); //$NON-NLS-1$ fShowInheritedMembersAction= new ShowInheritedMembersAction(this, false); showInheritedMethods(false); setSorter(new JavaElementSorter()); JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); } /** * Show inherited methods */ public void showInheritedMethods(boolean on) { MethodsContentProvider cprovider= (MethodsContentProvider) getContentProvider(); try { getTable().setRedraw(false); cprovider.showInheritedMethods(on); fShowInheritedMembersAction.setChecked(on); if (fLabelProvider != null) { if (on) { fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | JavaElementLabels.ALL_POST_QUALIFIED); } else { fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & (-1 ^ JavaElementLabels.ALL_POST_QUALIFIED)); } refresh(); } } 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$ } finally { getTable().setRedraw(true); } } /* * @see Viewer#inputChanged(Object, Object) */ protected void inputChanged(Object input, Object oldInput) { super.inputChanged(input, oldInput); } /** * Returns <code>true</code> if inherited methods are shown. */ public boolean isShowInheritedMethods() { return ((MethodsContentProvider) getContentProvider()).isShowInheritedMethods(); } /** * Saves the state of the filter actions */ public void saveState(IMemento memento) { fMemberFilterActionGroup.saveState(memento); 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) { fMemberFilterActionGroup.restoreState(memento); getControl().setRedraw(false); refresh(); getControl().setRedraw(true); boolean 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) { } /** * 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()); fMemberFilterActionGroup.contributeToToolBar(tbm); } /* * @see StructuredViewer#handleInvalidSelection(ISelection, ISelection) */ protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { // on change of input, try to keep selected methods stable by selecting a method with the same // signature: See #5466 List oldSelections= SelectionUtil.toList(invalidSelection); List newSelections= SelectionUtil.toList(newSelection); if (!oldSelections.isEmpty()) { ArrayList newSelectionElements= new ArrayList(newSelections); try { Object[] currElements= getFilteredChildren(getInput()); for (int i= 0; i < oldSelections.size(); i++) { Object curr= oldSelections.get(i); if (curr instanceof IMethod && !newSelections.contains(curr)) { IMethod method= (IMethod) curr; if (method.exists()) { IMethod similar= findSimilarMethod(method, currElements); if (similar != null) { newSelectionElements.add(similar); } } } } if (!newSelectionElements.isEmpty()) { newSelection= new StructuredSelection(newSelectionElements); } else if (currElements.length > 0) { newSelection= new StructuredSelection(currElements[0]); } } catch (JavaModelException e) { JavaPlugin.log(e); } } setSelection(newSelection); updateSelection(newSelection); } private IMethod findSimilarMethod(IMethod meth, Object[] elements) throws JavaModelException { String name= meth.getElementName(); String[] paramTypes= meth.getParameterTypes(); boolean isConstructor= meth.isConstructor(); for (int i= 0; i < elements.length; i++) { Object curr= elements[i]; if (curr instanceof IMethod && JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, (IMethod) curr)) { return (IMethod) curr; } } return null; } }
25,827
Bug 25827 Disposing of MemberFilterActionGroup
Build 2.0.2 and 2.1 When investigating an editor memory leak PR we found out that this group has a dispose method which is never called. When we then called from the editor it throw an exeption (viewer was disposed). Don't know if the group really needs dispose() if so it should get called.
resolved fixed
4534791
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T09:46:11Z
2002-11-07T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.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.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectAllAction; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of inut elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private IPropertyChangeListener fPropertyChangeListener; private MethodsViewer fMethodsViewer; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private boolean fIsEnableMemberFilter; private SashForm fTypeMethodsSplitter; private PageBook fViewerbook; private PageBook fPagebook; private Label fNoHierarchyShownLabel; private Label fEmptyTypesViewer; private ViewForm fTypeViewerViewForm; private ViewForm fMethodViewerViewForm; private CLabel fMethodViewerPaneLabel; private JavaUILabelProvider fPaneLabelProvider; private IDialogSettings fDialogSettings; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private int fCurrentOrientation; private EnableMemberFilterAction fEnableMemberFilterAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private IPartListener fPartListener; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; private SelectAllAction fSelectAllAction; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fHierarchyLifeCycle.setReconciled(JavaBasePreferencePage.reconcileJavaViews()); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fPropertyChangeListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doPropertyChange(event); } }; JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); fIsEnableMemberFilter= false; fInputHistory= new ArrayList(); fAllViewers= null; fViewActions= new ToggleViewAction[] { new ToggleViewAction(this, VIEW_ID_TYPE), new ToggleViewAction(this, VIEW_ID_SUPER), new ToggleViewAction(this, VIEW_ID_SUB) }; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); fHistoryDropDownAction= new HistoryDropDownAction(this); fHistoryDropDownAction.setEnabled(false); fToggleOrientationActions= new ToggleOrientationAction[] { new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE) }; fEnableMemberFilterAction= new EnableMemberFilterAction(this, false); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) {} public void partClosed(IWorkbenchPart part) {} public void partDeactivated(IWorkbenchPart part) {} public void partOpened(IWorkbenchPart part) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; } /** * Method doPropertyChange. * @param event */ private void doPropertyChange(PropertyChangeEvent event) { if (fMethodsViewer != null) { if (MembersOrderPreferencePage.PREF_OUTLINE_SORT_OPTION.equals(event.getProperty())) { fMethodsViewer.refresh(); } } } /** * Adds the entry if new. Inserted at the beginning of the history entries list. */ private void addHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { fInputHistory.remove(entry); } fInputHistory.add(0, entry); fHistoryDropDownAction.setEnabled(true); } private void updateHistoryEntries() { for (int i= fInputHistory.size() - 1; i >= 0; i--) { IJavaElement type= (IJavaElement) fInputHistory.get(i); if (!type.exists()) { fInputHistory.remove(i); } } fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty()); } /** * Goes to the selected entry, without updating the order of history entries. */ public void gotoHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { updateInput(entry); } } /** * Gets all history entries. */ public IJavaElement[] getHistoryEntries() { if (fInputHistory.size() > 0) { updateHistoryEntries(); } return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]); } /** * Sets the history entries */ public void setHistoryEntries(IJavaElement[] elems) { fInputHistory.clear(); for (int i= 0; i < elems.length; i++) { fInputHistory.add(elems[i]); } updateHistoryEntries(); } /** * Selects an member in the methods list or in the current hierarchy. */ public void selectMember(IMember member) { ICompilationUnit cu= member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { member= (IMember) cu.getOriginal(member); if (member == null) { return; } } if (member.getElementType() != IJavaElement.TYPE) { if (fHierarchyLifeCycle.isReconciled() && cu != null) { try { member= (IMember) EditorUtility.getWorkingCopy(member); if (member == null) { return; } } catch (JavaModelException e) { JavaPlugin.log(e); return; } } Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { methodControl.setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } else { Control viewerControl= getCurrentViewer().getControl(); if (viewerControl != null && !viewerControl.isDisposed()) { viewerControl.setFocus(); } getCurrentViewer().setSelection(new StructuredSelection(member), true); } } /** * @deprecated */ public IType getInput() { if (fInputElement instanceof IType) { return (IType) fInputElement; } return null; } /** * Sets the input to a new type * @deprecated */ public void setInput(IType type) { setInputElement(type); } /** * Returns the input element of the type hierarchy. * Can be of type <code>IType</code> or <code>IPackageFragment</code> */ public IJavaElement getInputElement() { return fInputElement; } /** * Sets the input to a new element. */ public void setInputElement(IJavaElement element) { if (element != null) { if (element instanceof IMember) { if (element.getElementType() != IJavaElement.TYPE) { element= ((IMember) element).getDeclaringType(); } ICompilationUnit cu= ((IMember) element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { element= cu.getOriginal(element); if (!element.exists()) { MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ return; } } } else { int kind= element.getElementType(); if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) { element= null; JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$ } } } if (element != null && !element.equals(fInputElement)) { addHistoryEntry(element); } updateInput(element); } /** * Changes the input to a new type */ private void updateInput(IJavaElement inputElement) { IJavaElement prevInput= fInputElement; fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e); clearInput(); return; } fPagebook.showPage(fTypeMethodsSplitter); if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } IType root= getSelectableType(fInputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); } } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); if (fPropertyChangeListener != null) { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } getSite().getPage().removePartListener(fPartListener); if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); KeyListener keyListener= createKeyListener(); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW); fAllViewers= new TypeHierarchyViewer[3]; fAllViewers[VIEW_ID_SUPER]= superTypesViewer; fAllViewers[VIEW_ID_SUB]= subTypesViewer; fAllViewers[VIEW_ID_TYPE]= vajViewer; int currViewerIndex; try { currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW); if (currViewerIndex < 0 || currViewerIndex > 2) { currViewerIndex= VIEW_ID_TYPE; } } catch (NumberFormatException e) { currViewerIndex= VIEW_ID_TYPE; } fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setInput(fAllViewers[i]); } // force the update fCurrentViewerIndex= -1; setView(currViewerIndex); return fViewerbook; } private KeyListener createKeyListener() { return new KeyAdapter() { public void keyReleased(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F5) { updateHierarchyViewer(); return; } else if (event.character == SWT.DEL){ if (fCCPActionGroup.getDeleteAction().isEnabled()) fCCPActionGroup.getDeleteAction().run(); return; } } viewPartKeyShortcuts(event); } }; } private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) { typesViewer.getControl().setVisible(false); typesViewer.getControl().addKeyListener(keyListener); typesViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillTypesViewerContextMenu(typesViewer, menu); } }, cotextHelpId, getSite()); typesViewer.addSelectionChangedListener(fSelectionChangedListener); } private Control createMethodViewerControl(Composite parent) { fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this); fMethodsViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillMethodsViewerContextMenu(menu); } }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite()); fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener); Control control= fMethodsViewer.getTable(); control.addKeyListener(createKeyListener()); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK; for (int i= 0; i < fAllViewers.length; i++) { addDragAdapters(fAllViewers[i], ops, transfers); addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers); } addDragAdapters(fMethodsViewer, ops, transfers); //dnd on empty hierarchy DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT); dropTarget.setTransfer(transfers); dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0])); } private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){ TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new TypeHierarchyTransferDropAdapter(this, viewer) }; viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners)); } private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){ Control control= viewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(viewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners)); } private void viewPartKeyShortcuts(KeyEvent event) { if (event.stateMask == SWT.CTRL) { if (event.character == '1') { setView(VIEW_ID_TYPE); } else if (event.character == '2') { setView(VIEW_ID_SUPER); } else if (event.character == '3') { setView(VIEW_ID_SUB); } } } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ MenuManager menu= new MenuManager(); menu.add(fFocusOnTypeAction); fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel)); fPagebook.showPage(fNoHierarchyShownLabel); int orientation; try { orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION); if (orientation < 0 || orientation > 2) { orientation= VIEW_ORIENTATION_VERTICAL; } } catch (NumberFormatException e) { orientation= VIEW_ORIENTATION_VERTICAL; } // force the update fCurrentOrientation= -1; // will fill the main tool bar setOrientation(orientation); // 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); } WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); fActionGroups= new CompositeActionGroup(new ActionGroup[] { new NewWizardsActionGroup(this.getSite()), new OpenEditorActionGroup(this), new OpenViewActionGroup(this), new ShowActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new GenerateActionGroup(this), new JavaSearchActionGroup(this)}); fActionGroups.fillActionBars(actionBars); fSelectAllAction= new SelectAllAction(fMethodsViewer); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction); initDragAndDrop(); } /** * called from ToggleOrientationAction. * @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL */ public void setOrientation(int orientation) { if (fCurrentOrientation != orientation) { boolean methodViewerNeedsUpdate= false; if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed() && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) { if (orientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(false); enableMemberFilter(false); updateMethodViewer(null); } else { if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(true); methodViewerNeedsUpdate= true; } boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL; fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL); } updateMainToolbar(orientation); fTypeMethodsSplitter.layout(); } for (int i= 0; i < fToggleOrientationActions.length; i++) { fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation()); } fCurrentOrientation= orientation; if (methodViewerNeedsUpdate) { updateMethodViewer(fSelectedType); } fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation); } } private void updateMainToolbar(int orientation) { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager tbmanager= actionBars.getToolBarManager(); if (orientation == VIEW_ORIENTATION_HORIZONTAL) { clearMainToolBar(tbmanager); ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP); fillMainToolBar(new ToolBarManager(typeViewerToolBar)); fTypeViewerViewForm.setTopLeft(typeViewerToolBar); } else { fTypeViewerViewForm.setTopLeft(null); fillMainToolBar(tbmanager); } } private void fillMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.add(fHistoryDropDownAction); for (int i= 0; i < fViewActions.length; i++) { tbmanager.add(fViewActions[i]); } tbmanager.update(false); } private void clearMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.update(false); } /** * Creates the context menu for the hierarchy viewers */ private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) { JavaPlugin.createStandardGroups(menu); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS)); // viewer entries viewer.contributeToContextMenu(menu); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction); menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction); fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } /** * Creates the context menu for the method viewer */ private void fillMethodsViewerContextMenu(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries fMethodsViewer.contributeToContextMenu(menu); if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) { menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction); } fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); // //menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer)); // addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection()); // ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(this, false)}, fMethodsViewer); // // // XXX workaround until we have fully converted the code to use the new action groups // fActionGroups.get(2).fillContextMenu(menu); // fActionGroups.get(3).fillContextMenu(menu); // fActionGroups.get(4).fillContextMenu(menu); } 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; IJavaElement openable= (IJavaElement) ((IJavaElement) element).getOpenable(); IResource resource= openable.getResource(); 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); } /** * Toggles between the empty viewer page and the hierarchy */ private void setViewerVisibility(boolean showHierarchy) { if (showHierarchy) { fViewerbook.showPage(getCurrentViewer().getControl()); } else { fViewerbook.showPage(fEmptyTypesViewer); } } /** * Sets the member filter. <code>null</code> disables member filtering. */ private void setMemberFilter(IMember[] memberFilter) { Assert.isNotNull(fAllViewers); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setMemberFilter(memberFilter); } } private IType getSelectableType(IJavaElement elem) { if (elem.getElementType() != IJavaElement.TYPE) { return null; //(IType) getCurrentViewer().getTreeRootType(); } else { return (IType) elem; } } private void internalSelectType(IMember elem, boolean reveal) { TypeHierarchyViewer viewer= getCurrentViewer(); viewer.removeSelectionChangedListener(fSelectionChangedListener); viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal); viewer.addSelectionChangedListener(fSelectionChangedListener); } private void internalSelectMember(IMember member) { fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener); fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY); fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener); } /** * When the input changed or the hierarchy pane becomes visible, * <code>updateHierarchyViewer<code> brings up the correct view and refreshes * the current tree */ private void updateHierarchyViewer() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) { setViewerVisibility(true); } } else { fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$ setViewerVisibility(false); } } } private void updateMethodViewer(IType input) { if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input == fMethodsViewer.getInput()) { if (input != null) { fMethodsViewer.refresh(); } } else 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()); fSelectAllAction.setEnabled(true); } else { typeSelectionChanged(e.getSelection()); fSelectAllAction.setEnabled(false); } } private void methodSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (fIsEnableMemberFilter) { IMember[] memberFilter= null; if (nSelected > 0) { memberFilter= new IMember[nSelected]; selected.toArray(memberFilter); } setMemberFilter(memberFilter); updateHierarchyViewer(); updateTitle(); internalSelectType(fSelectedType, true); } if (nSelected == 1) { revealElementInEditor(selected.get(0), fMethodsViewer); } } } private void typeSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (nSelected != 0) { List types= new ArrayList(nSelected); for (int i= nSelected-1; i >= 0; i--) { Object elem= selected.get(i); if (elem instanceof IType && !types.contains(elem)) { types.add(elem); } } if (types.size() == 1) { fSelectedType= (IType) types.get(0); updateMethodViewer(fSelectedType); } else if (types.size() == 0) { // method selected, no change } if (nSelected == 1) { revealElementInEditor(selected.get(0), getCurrentViewer()); } } else { fSelectedType= null; updateMethodViewer(null); } } } private void revealElementInEditor(Object elem, Viewer originViewer) { // only allow revealing when the type hierarchy is the active pagae // no revealing after selection events due to model changes if (getSite().getPage().getActivePart() != this) { return; } if (fSelectionProviderMediator.getViewerInFocus() != originViewer) { return; } IEditorPart editorPart= EditorUtility.isOpenInEditor(elem); if (editorPart != null && (elem instanceof IJavaElement)) { try { getSite().getPage().removePartListener(fPartListener); EditorUtility.openInEditor(elem, false); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } catch (CoreException e) { JavaPlugin.log(e); } } } private Display getDisplay() { if (fPagebook != null && !fPagebook.isDisposed()) { return fPagebook.getDisplay(); } return null; } private boolean isChildVisible(Composite pb, Control child) { Control[] children= pb.getChildren(); for (int i= 0; i < children.length; i++) { if (children[i] == child && children[i].isVisible()) return true; } return false; } private void updateTitle() { String viewerTitle= getCurrentViewer().getTitle(); String tooltip; String title; if (fInputElement != null) { String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) }; title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$ tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$ } else { title= viewerTitle; tooltip= viewerTitle; } setTitle(title); setTitleToolTip(tooltip); } private void updateToolbarButtons() { boolean isType= fInputElement instanceof IType; for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; if (action.getViewerIndex() == VIEW_ID_TYPE) { action.setEnabled(fInputElement != null); } else { action.setEnabled(isType); } } } /** * Sets the current view (see view id) * called from ToggleViewAction. Must be called after creation of the viewpart. */ public void setView(int viewerIndex) { Assert.isNotNull(fAllViewers); if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) { fCurrentViewerIndex= viewerIndex; updateHierarchyViewer(); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { internalSelectType(getSelectableType(fInputElement), false); currSelection= getCurrentViewer().getSelection(); } if (!fIsEnableMemberFilter) { typeSelectionChanged(currSelection); } } updateTitle(); fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex); getCurrentViewer().getTree().setFocus(); } for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; action.setChecked(fCurrentViewerIndex == action.getViewerIndex()); } } /** * Gets the curret active view index. */ public int getViewIndex() { return fCurrentViewerIndex; } private TypeHierarchyViewer getCurrentViewer() { return fAllViewers[fCurrentViewerIndex]; } /** * called from EnableMemberFilterAction. * Must be called after creation of the viewpart. */ public void enableMemberFilter(boolean on) { if (on != fIsEnableMemberFilter) { fIsEnableMemberFilter= on; if (!on) { IType methodViewerInput= (IType) fMethodsViewer.getInput(); setMemberFilter(null); updateHierarchyViewer(); updateTitle(); if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) { // avoid that the method view changes content by selecting the previous input internalSelectType(methodViewerInput, true); } else if (fSelectedType != null) { // choose a input that exists internalSelectType(fSelectedType, true); updateMethodViewer(fSelectedType); } } else { methodSelectionChanged(fMethodsViewer.getSelection()); } } fEnableMemberFilterAction.setChecked(on); } /** * Called from ITypeHierarchyLifeCycleListener. * Can be called from any thread */ private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { if (fPagebook != null && !fPagebook.isDisposed()) { doTypeHierarchyChangedOnViewers(changedTypes); } } }); } } private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } fMethodsViewer.refresh(); updateHierarchyViewer(); } else { // elements in hierarchy modified fMethodsViewer.refresh(); 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) { IJavaElement elem= (IJavaElement) input; if (elem instanceof IMember) { return elem; } else { int kind= elem.getElementType(); if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) { return elem; } } } return null; } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { String handleIndentifier= fInputElement.getHandleIdentifier(); if (fInputElement instanceof IType) { ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) { // for startup performance reasons do not try to recover huge hierarchies handleIndentifier= null; } } memento.putString(TAG_INPUT, handleIndentifier); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fMethodsViewer.saveState(memento); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (input != null && !input.exists()) { input= null; } } setInputElement(input); Integer viewerIndex= memento.getInteger(TAG_VIEW); if (viewerIndex != null) { setView(viewerIndex.intValue()); } Integer orientation= memento.getInteger(TAG_ORIENTATION); if (orientation != null) { setOrientation(orientation.intValue()); } Integer ratio= memento.getInteger(TAG_RATIO); if (ratio != null) { fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() }); } ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } //String selectionId= memento.getString(TAG_SELECTION); // do not restore type hierarchy contents // if (selectionId != null) { // IJavaElement elem= JavaCore.create(selectionId); // if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) { // internalSelectType((IMember)elem, false); // } // } fMethodsViewer.restoreState(memento); } /** * Link selection to active editor. */ private void editorActivated(IEditorPart editor) { if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) { return; } if (fInputElement == null) { // no type hierarchy shown return; } IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class); try { TypeHierarchyViewer currentViewer= getCurrentViewer(); if (elem instanceof IClassFile) { IType type= ((IClassFile)elem).getType(); if (currentViewer.isElementShown(type)) { internalSelectType(type, true); updateMethodViewer(type); } } else if (elem instanceof ICompilationUnit) { IType[] allTypes= ((ICompilationUnit)elem).getAllTypes(); for (int i= 0; i < allTypes.length; i++) { if (currentViewer.isElementShown(allTypes[i])) { internalSelectType(allTypes[i], true); updateMethodViewer(allTypes[i]); return; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return fInputElement; } }
25,827
Bug 25827 Disposing of MemberFilterActionGroup
Build 2.0.2 and 2.1 When investigating an editor memory leak PR we found out that this group has a dispose method which is never called. When we then called from the editor it throw an exeption (viewer was disposed). Don't know if the group really needs dispose() if so it should get called.
resolved fixed
4534791
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T09:46:11Z
2002-11-07T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/MemberFilterActionGroup.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.actions; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.viewsupport.MemberFilter; import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterAction; /** * Action Group that contributes filter buttons for a view parts showing * methods and fields. Contributed filters are: hide fields, hide static * members and hide non-public members. * <p> * The action group installs a filter on a structured viewer. The filter is connected * to the actions installed in the view part's toolbar menu and is updated when the * state of the buttons changes. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class MemberFilterActionGroup extends ActionGroup { public static final int FILTER_NONPUBLIC= MemberFilter.FILTER_NONPUBLIC; public static final int FILTER_STATIC= MemberFilter.FILTER_STATIC; public static final int FILTER_FIELDS= MemberFilter.FILTER_FIELDS; 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 MemberFilterAction[] fFilterActions; private MemberFilter fFilter; private StructuredViewer fViewer; private String fViewerId; /** * Creates a new <code>MemberFilterActionGroup</code>. * * @param viewer the viewer to be filtered * @param viewerId a unique id of the viewer. Used as a key to to store * the last used filter settings in the preference store */ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId) { fViewer= viewer; fViewerId= viewerId; // get initial values IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); boolean doHideFields= store.getBoolean(getPreferenceKey(FILTER_FIELDS)); boolean doHideStatic= store.getBoolean(getPreferenceKey(FILTER_STATIC)); boolean doHidePublic= store.getBoolean(getPreferenceKey(FILTER_NONPUBLIC)); fFilter= new MemberFilter(); if (doHideFields) fFilter.addFilter(FILTER_FIELDS); if (doHideStatic) fFilter.addFilter(FILTER_STATIC); if (doHidePublic) fFilter.addFilter(FILTER_NONPUBLIC); // fields String title= ActionMessages.getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$ String helpContext= IJavaHelpContextIds.FILTER_FIELDS_ACTION; MemberFilterAction hideFields= new MemberFilterAction(this, title, FILTER_FIELDS, helpContext, doHideFields); hideFields.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_fields.description")); //$NON-NLS-1$ hideFields.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_fields.tooltip")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$ // static title= ActionMessages.getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_STATIC_ACTION; MemberFilterAction hideStatic= new MemberFilterAction(this, title, FILTER_STATIC, helpContext, doHideStatic); hideStatic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_static.description")); //$NON-NLS-1$ hideStatic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_static.tooltip")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$ // non-public title= ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_PUBLIC_ACTION; MemberFilterAction hideNonPublic= new MemberFilterAction(this, title, FILTER_NONPUBLIC, helpContext, doHidePublic); hideNonPublic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.description")); //$NON-NLS-1$ hideNonPublic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.tooltip")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$ // order corresponds to order in toolbar fFilterActions= new MemberFilterAction[] { hideFields, hideStatic, hideNonPublic }; fViewer.addFilter(fFilter); } private String getPreferenceKey(int filterProperty) { return "MemberFilterActionGroup." + fViewerId + '.' + String.valueOf(filterProperty); //$NON-NLS-1$ } /** * Sets the member filters. * * @param filterProperty the filter to be manipulated. Valid values are <code>FILTER_FIELDS</code>, * <code>FILTER_PUBLIC</code>, and <code>FILTER_PRIVATE</code> as defined by this action * group * @param set if <code>true</code> the given filter is installed. If <code>false</code> the * given filter is removed * . */ public void setMemberFilter(int filterProperty, boolean set) { setMemberFilters(new int[] {filterProperty}, new boolean[] {set}, true); } private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, boolean refresh) { if (propertyKeys.length == 0) return; Assert.isTrue(propertyKeys.length == propertyValues.length); for (int i= 0; i < propertyKeys.length; i++) { int filterProperty= propertyKeys[i]; boolean set= propertyValues[i]; if (set) { fFilter.addFilter(filterProperty); } else { fFilter.removeFilter(filterProperty); } IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); for (int j= 0; j < fFilterActions.length; j++) { int currProperty= fFilterActions[j].getFilterProperty(); if (currProperty == filterProperty) { fFilterActions[j].setChecked(set); } store.setValue(getPreferenceKey(currProperty), hasMemberFilter(currProperty)); } } if (refresh) { fViewer.getControl().setRedraw(false); BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() { public void run() { fViewer.refresh(); } }); fViewer.getControl().setRedraw(true); } } /** * Returns <code>true</code> if the given filter is installed. * * @param filterProperty the filter to be tested. Valid values are <code>FILTER_FIELDS</code>, * <code>FILTER_PUBLIC</code>, and <code>FILTER_PRIVATE</code> as defined by this action * group */ public boolean hasMemberFilter(int filterProperty) { return fFilter.hasFilter(filterProperty); } /** * Saves the state of the filter actions in a memento. * * @param memento the memento to which the state is saved */ public void saveState(IMemento memento) { memento.putString(TAG_HIDEFIELDS, String.valueOf(hasMemberFilter(FILTER_FIELDS))); memento.putString(TAG_HIDESTATIC, String.valueOf(hasMemberFilter(FILTER_STATIC))); memento.putString(TAG_HIDENONPUBLIC, String.valueOf(hasMemberFilter(FILTER_NONPUBLIC))); } /** * Restores the state of the filter actions from a memento. * <p> * Note: This method does not refresh the viewer. * </p> * @param memento the memento from which the state is restored */ public void restoreState(IMemento memento) { setMemberFilters( new int[] {FILTER_FIELDS, FILTER_STATIC, FILTER_NONPUBLIC}, new boolean[] { Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)).booleanValue(), Boolean.valueOf(memento.getString(TAG_HIDESTATIC)).booleanValue(), Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)).booleanValue() }, false); } /* (non-Javadoc) * @see ActionGroup#fillActionBars(IActionBars) */ public void fillActionBars(IActionBars actionBars) { contributeToToolBar(actionBars.getToolBarManager()); }; /** * Adds the filter actions to the given tool bar * * @param tbm the tool bar to which the actions are added */ public void contributeToToolBar(IToolBarManager tbm) { tbm.add(fFilterActions[0]); // fields tbm.add(fFilterActions[1]); // static tbm.add(fFilterActions[2]); // public } /* (non-Javadoc) * @see ActionGroup#dispose() */ public void dispose() { fViewer.removeFilter(fFilter); super.dispose(); } }
26,272
Bug 26272 Add _$ to list of prefixes for field getter/setter creation [code manipulation]
A common convention is to use _ for instance variables and _$ for static instance variables. Although _ will be stripped by default, it would be useful if _$ was also in the list. Of course, this is settable for individual users (which I've already done) but since it is not an uncommon coding convention (and won't harm anyone in general if present) then I would vote for it to be added to the getter/setter generation prefixes.
verified fixed
b60bab9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T11:00:19Z
2002-11-14T13:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.WorkbenchChainedTextFontFieldEditor; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.ui.text.IJavaColorConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; /** * Preference constants used in the JDT-UI preference store. Clients should only read the * JDT-UI preference store using these values. Clients are not allowed to modify the * preference store programmatically. * * @since 2.0 */ public class PreferenceConstants { private PreferenceConstants() { } /** * A named preference that controls return type rendering of methods in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> return types * are rendered * </p> */ public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.jdt.ui.methodreturntype";//$NON-NLS-1$ /** * A named preference that controls if override indicators are rendered in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> override * indicators are rendered * </p> */ public static final String APPEARANCE_OVERRIDE_INDICATOR= "org.eclipse.jdt.ui.overrideindicator";//$NON-NLS-1$ /** * A named preference that defines the pattern used for package name compression. * <p> * Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern * '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'. * </p> */ public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$ /** * A named preference that controls if package name compression is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW */ public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$ /** * A named preference that controls if empty inner packages are folded in * the hierarchical mode of the package explorer. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> empty * inner packages are folded. * </p> * @since 2.1 */ public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$ /** * A named preference that controls if prefix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of prefixes to be removed from a local variable to compute setter * and gettter names. * <p> * Value is of type <code>String</code>: comma separated list of prefixed * </p> * * @see #CODEGEN_USE_GETTERSETTER_PREFIX */ public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$ /** * A named preference that controls if suffix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of suffixes to be removed from a local variable to compute setter * and getter names. * <p> * Value is of type <code>String</code>: comma separated list of suffixes * </p> * * @see #CODEGEN_USE_GETTERSETTER_SUFFIX */ public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ /** * A name preference that controls if a JavaDoc stub gets added to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String CODEGEN__JAVADOC_STUBS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$ /** * A named preference that controls if a non-javadoc comment gets added to methods generated via the * "Override Methods" operation. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$ /** * A named preference that controls if a file comment gets added to newly created files. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$ /** * A named preference that holds a list of comma separated package names. The list specifies the import order used by * the "Organize Imports" opeation. * <p> * Value is of type <code>String</code>: comma separated list of package names * </p> */ public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.jdt.ui.importorder"; //$NON-NLS-1$ /** * A named preference that specifies the number of imports added before a star-import declaration is used. * <p> * Value is of type <code>Int</code>: positive value specifing the number of non star-import is used * </p> */ public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.jdt.ui.ondemandthreshold"; //$NON-NLS-1$ /** * A named preferences that controls if types that start with a lower case letters get added by the * "Organize Import" operation. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.jdt.ui.ignorelowercasenames"; //$NON-NLS-1$ /** * A named preference that speficies whether children of a compilation unit are shown in the package explorer. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String SHOW_CU_CHILDREN= "org.eclipse.jdt.ui.packages.cuchildren"; //$NON-NLS-1$ /** * A named preference that controls whether the package explorer's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the hierarchy view's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_TYPEHIERARCHY_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the browsing view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether new projects are generated using source and output folder. * <p> * Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and * output folder. If <code>false</code> source and output folder equals to the project. * </p> */ public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ /** * A named preference that specifies the source folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ /** * A named preference that specifies the output folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ /** * A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library * consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the * JRE on the new project's classpath. * <p> * Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries. * <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients * should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string * and the methods <code>decodeJRELibraryDescription(String)</code> and <code> * decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array * of classpath entries from an encoded string. * </p> * * @see #NEWPROJECT_JRELIBRARY_INDEX * @see #encodeJRELibrary(String, IClasspathEntry[]) * @see #decodeJRELibraryDescription(String) * @see #decodeJRELibraryClasspathEntries(String) */ public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$ /** * A named preferences that specifies the current active JRE library. * <p> * Value is of type <code>Int</code>: an index into the list of possible JRE libraries. * </p> * * @see #NEWPROJECT_JRELIBRARY_LIST */ public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$ /** * A named preference that controls if a new type hierarchy gets opened in a * new type hierarchy perspective or inside the type hierarchy view part. * <p> * Value is of type <code>String</code>: possible values are <code> * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code> * OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>. * </p> * * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART */ public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$ /** * A named preference that controls the behaviour when double clicking on a container in the packages view. * <p> * Value is of type <code>String</code>: possible values are <code> * DOUBLE_CLICK_GOES_INTO</code> or <code> * DOUBLE_CLICK_EXPANDS</code>. * </p> * * @see #DOUBLE_CLICK_EXPANDS * @see #DOUBLE_CLICK_GOES_INTO */ public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$ /** * A named preference that controls whether Java views update their presentation while editing or when saving the * content of an editor. * <p> * Value is of type <code>String</code>: possible values are <code> * UPDATE_ON_SAVE</code> or <code> * UPDATE_WHILE_EDITING</code>. * </p> * * @see #UPDATE_ON_SAVE * @see #UPDATE_WHILE_EDITING */ public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$ /** * A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard. * <p> * Value is of type <code>String</code>. * </p> */ public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$ /** * A named preference that controls whether bracket matching highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight matching brackets. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$ /** * A named preference that controls whether the current line highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight the current line. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$ /** * A named preference that controls whether the print margin is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$ /** * A named preference that holds the color used to render the print margin. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$ /** * Print margin column. Int value. */ public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$ /** * A named preference that holds the color used for the find/replace scope. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; /** * A named preference that specifies if the editor uses spaces for tabs. * <p> * Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used * in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab * key. * </p> */ public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$ /** * A named preference that holds the number of spaces used per tab in the editor. * <p> * Value is of type <code>Int</code>: positive int value specifying the number of * spaces per tab. * </p> */ public final static String EDITOR_TAB_WIDTH= "org.eclipse.jdt.ui.editor.tab.width"; //$NON-NLS-1$ /** * A named preference that controls whether the outline view selection * should stay in sync with with the element at the current cursor position. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ /** * A named preference that controls if correction indicators are shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows problem indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render problem indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_PROBLEM_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$ /**PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; * A named preference that controls whether the editor shows warning indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render warning indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_WARNING_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows task indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render task indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_TASK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows bookmark * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render bookmark indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_BOOKMARK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows search * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render search indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_SEARCH_RESULT_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows unknown * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render unknown * indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_UNKNOWN_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows error * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows warning * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows task * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * bookmark indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * search result indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * unknown indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close strings' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'wrap strings' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close brackets' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close java docs' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'add JavaDoc tags' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$ /** * A named preference that controls whether the 'format Javadoc tags' * feature is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_FORMAT_JAVADOCS= "formatJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart paste' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart home-end' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; /** * A named preference that controls if temporary problems are evaluated and shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$ /** * A named preference that controls if the overview ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$ /** * A named preference that controls if the line number ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$ /** * A named preference that holds the color used to render line numbers inside the line number ruler. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @see #EDITOR_LINE_NUMBER_RULER */ public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$ /** * A named preference that holds the color used to render linked positions inside code templates. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$ /** * A named preference that holds the color used as the text foreground. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; /** * A named preference that describes if the system default foreground color * is used as the text foreground. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; /** * A named preference that holds the color used as the text background. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; /** * A named preference that describes if the system default background color * is used as the text foreground. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; /** * Preference key suffix for bold text style preference keys. */ public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$ /** * A named preference that holds the color used to render multi line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT; /** * A named preference that controls whether multi line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render single line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT; /** * A named preference that controls whether sinle line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD; /** * A named preference that controls whether keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render string constants. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING; /** * A named preference that controls whether string constants are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT; /** * A named preference that controls whether Java default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD; /** * A named preference that controls whether javadoc keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG; /** * A named preference that controls whether javadoc tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc links. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK; /** * A named preference that controls whether javadoc links are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT; /** * A named preference that controls whether javadoc default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used for 'linked-mode' underline. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$ /** * A named preference that controls whether hover tooltips in the editor are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when no control key is * pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 */ public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 */ public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>SHIFT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>ALT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code>, * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that no hover should be shown for the given key modifiers. * @since 2.1 */ public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that the default hover should be shown for the given key * modifiers. The default hover is described by the * <code>EDITOR_DEFAULT_HOVER</code> property. * @since 2.1 */ public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$ /** * A named preference that defines the hover named the 'default hover'. * Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> *@since 2.1 */ public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$ /** * A named preference that controls if segmented view (show selected element only) is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist gets auto activated. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$ /** * A name preference that holds the auto activation delay time in milli seconds. * <p> * Value is of type <code>Int</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$ /** * A named preference that controls if code assist contains only visible proposals. * <p> * Value is of type <code>Boolean</code>. if <code>true<code> code assist only contains visible members. If * <code>false</code> all members are included. * </p> */ public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist inserts a * proposal automatically if only one proposal is available. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist adds import * statements. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist only inserts * completions. If set to false the proposals can also _replace_ code. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$ /** * A named preference that controls whether code assist proposals filtering is case sensitive or not. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$ /** * A named preference that defines if code assist proposals are sorted in alphabetical order. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical * order. If <code>false</code> that are unsorted. * </p> */ public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$ /** * A named preference that controls if argument names are filled in when a method is selected from as list * of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$ /** * A named preference that controls if method arguments are guessed when a * method is selected from as list of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Java code. * <p> * Value is of type <code>Sring</code>. All characters that trigger auto code assist in Java code. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Javadoc. * <p> * Value is of type <code>Sring</code>. All characters that trigger auto code assist in Javadoc. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used for parameter hints. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ /** * A named preference that controls the behaviour of the refactoring wizard for showing the error page. * <p> * Value is of type <code>String</code>. Valid values are: * <code>REFACTOR_FATAL_SEVERITY</code>, * <code>REFACTOR_ERROR_SEVERITY</code>, * <code>REFACTOR_WARNING_SEVERITY</code> * <code>REFACTOR_INFO_SEVERITY</code>, * <code>REFACTOR_OK_SEVERITY</code>. * </p> * * @see #REFACTOR_FATAL_SEVERITY * @see #REFACTOR_ERROR_SEVERITY * @see #REFACTOR_WARNING_SEVERITY * @see #REFACTOR_INFO_SEVERITY * @see #REFACTOR_OK_SEVERITY */ public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$ /** * A named preference thet controls whether all dirty editors are automatically saved before a refactoring is * executed. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$ /** * A named preference that controls if the Java Browsing views are linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #LINK_PACKAGES_TO_EDITOR */ public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls the layout of the Java Browsing views vertically. Boolean value. * <p> * Value is of type <code>Boolean</code>. If <code>true<code> the views are stacked vertical. * If <code>false</code> they are stacked horizontal. * </p> */ public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.jdt.ui.browsing.stackVertically"; //$NON-NLS-1$ /** * A named preference that controls if templates are formatted when applied. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 2.1 */ public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.jdt.ui.template.format"; //$NON-NLS-1$ public static void initializeDefaultValues(IPreferenceStore store) { store.setDefault(PreferenceConstants.EDITOR_SHOW_HOVER, true); store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); // JavaBasePreferencePage store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false); store.setDefault(PreferenceConstants.LINK_BROWSING_VIEW_TO_EDITOR, true); store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS); store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING); // AppearancePreferencePage store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false); store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true); store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$ store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true); // ImportOrganizePreferencePage store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); // ClasspathVariablesPreferencePage // CodeFormatterPreferencePage // CompilerPreferencePage // no initialization needed // RefactoringPreferencePage store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY); store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); // TemplatePreferencePage store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); // CodeGenerationPreferencePage store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, false); store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, false); store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, "f, fg, _, m_"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEGEN__JAVADOC_STUBS, true); store.setDefault(PreferenceConstants.CODEGEN__NON_JAVADOC_COMMENTS, false); store.setDefault(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); // JavaEditorPreferencePage /* * Ensure that the display is accessed only in the UI thread. * Ensure that there are no side effects of switching the thread. */ final RGB[] rgbs= new RGB[3]; final Display display= Display.getDefault(); display.syncExec(new Runnable() { public void run() { Color c= display.getSystemColor(SWT.COLOR_GRAY); rgbs[0]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND); rgbs[1]= c.getRGB(); c= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); rgbs[2]= c.getRGB(); } }); store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, rgbs[0]); store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224)); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180)); store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0 , 128)); store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, 200 , 45)); store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, 255)); store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, 164, 99)); store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new RGB(192, 192, 192)); store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, false); store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true); store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, false); store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true); store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0)); WorkbenchChainedTextFontFieldEditor.startPropagate(store, JFaceResources.TEXT_FONT); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200 , 100)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgbs[1]); store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgbs[2]); store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, new RGB(127, 127, 159)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); //$NON-NLS-1$ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500); store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true); store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false); store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true); store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false); store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true); store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, true); store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); store.setDefault(PreferenceConstants.EDITOR_DEFAULT_HOVER, JavaPlugin.ID_BESTMATCH_HOVER); store.setDefault(PreferenceConstants.EDITOR_NONE_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); store.setDefault(PreferenceConstants.EDITOR_CTRL_HOVER, JavaPlugin.ID_SOURCE_HOVER); store.setDefault(PreferenceConstants.EDITOR_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); store.setDefault(PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); store.setDefault(PreferenceConstants.EDITOR_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); JavadocPreferencePage.initDefaults(store); NewJavaProjectPreferencePage.initDefaults(store); MembersOrderPreferencePage.initDefaults(store); } /** * Returns the JDT-UI preference store. * * @return the JDT-UI preference store */ public IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /** * Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>. * * @param description a string value describing the JRE library. The description is used * to indentify the JDR library in the UI * @param entries an array of classpath entries to be encoded * * @return the encoded string. */ public static String encodeJRELibrary(String description, IClasspathEntry[] entries) { return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries); } /** * Decodes an encoded JRE library and returns its description string. * * @return the description of an encoded JRE library * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static String decodeJRELibraryDescription(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); } /** * Decodes an encoded JRE library and returns its classpath entries. * * @return the array of classpath entries of an encoded JRE library. * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); } /** * Returns the current configuration for the JRE to be used as default in new Java projects. * This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST * </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>. * * @return the current default set of classpath entries * * @see #NEWPROJECT_JRELIBRARY_LIST * @see #NEWPROJECT_JRELIBRARY_INDEX */ public static IClasspathEntry[] getDefaultJRELibrary() { return NewJavaProjectPreferencePage.getDefaultJRELibrary(); } }
26,481
Bug 26481 Working Set Selection (Java only) is unuseably slow. [filters]
When I try to create a new Working Set in 2.1 M2, as soon as I expand a project in the tree view, my CPU is pegged for ~1minute. Typing in the "Name" box is incredibly slow. In short, it is nearly unuseable because it is so slow too respond. Win NT, 512MB, ~2400 classes in workspace (split evenly over 2 projects). -Andrew
resolved fixed
67b1d3f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T11:26:17Z
2002-11-15T14:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/JavaWorkingSetPage.java
26,271
Bug 26271 Link-Like navigation: Pixel not removed
20021113 1. Create class public class A { private void fill(StringBuffer buffer, String s) { buffer.append(s); } } 2. CTRL pressed all the time 3. move the mouse over 'append' 4. While still presing CTRL go over 's' (same line) 5. You can see that there is still a blue pixel under 'append'
resolved fixed
48770ef
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T15:21:04Z
2002-11-14T13:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.AnnotationRulerColumn; import org.eclipse.jface.text.source.CompositeRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.IVerticalRulerColumn; import org.eclipse.jface.text.source.LineNumberRulerColumn; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPartService; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.editors.text.DefaultEncodingSupport; import org.eclipse.ui.editors.text.IEncodingSupport; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.texteditor.AddTaskAction; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.StatusTextEditor; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.ui.text.IColorManager; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; /** * Java specific text editor. */ public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider { /** * "Smart" runnable for updating the outline page's selection. */ class OutlinePageSelectionUpdater implements Runnable { /** Has the runnable already been posted? */ private boolean fPosted= false; public OutlinePageSelectionUpdater() { } /* * @see Runnable#run() */ public void run() { synchronizeOutlinePageSelection(); fPosted= false; } /** * Posts this runnable into the event queue. */ public void post() { if (fPosted) return; Shell shell= getSite().getShell(); if (shell != null & !shell.isDisposed()) { fPosted= true; shell.getDisplay().asyncExec(this); } } }; class SelectionChangedListener implements ISelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; /** * Link mode. */ class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener { /** The session is active. */ private boolean fActive; /** The currently active style range. */ private IRegion fActiveRegion; /** The hand cursor. */ private Cursor fCursor; /** The default cursor. */ private Cursor fDefaultCursor; /** The link color. */ private Color fColor; public void deactivate() { if (!fActive) return; repairRepresentation(); fActive= false; } public void install() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; updateColor(sourceViewer); sourceViewer.addTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.addDocumentListener(this); text.addKeyListener(this); text.addMouseListener(this); text.addMouseMoveListener(this); text.addFocusListener(this); text.addPaintListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.addPropertyChangeListener(this); } public void uninstall() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; sourceViewer.removeTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.removeDocumentListener(this); text.removeKeyListener(this); text.removeMouseListener(this); text.removeMouseMoveListener(this); text.removeFocusListener(this); text.removePaintListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.removePropertyChangeListener(this); if (fColor != null) { fColor.dispose(); fColor= null; } if (fCursor != null) { fCursor.dispose(); fCursor= null; } } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(JavaEditor.LINK_COLOR)) { ISourceViewer viewer= getSourceViewer(); if (viewer != null) updateColor(viewer); } } private void updateColor(ISourceViewer viewer) { if (fColor != null) fColor.dispose(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display); } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } private void repairRepresentation() { if (fActiveRegion == null) return; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { resetCursor(viewer); int offset= fActiveRegion.getOffset(); int length= fActiveRegion.getLength(); // remove style if (viewer instanceof ITextViewerExtension2) ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length); else viewer.invalidateTextPresentation(); // remove underline offset -= viewer.getVisibleRegion().getOffset(); StyledText text= viewer.getTextWidget(); text.redrawRange(offset, length, true); } fActiveRegion= null; } private IJavaElement getInput(JavaEditor editor) { if (editor == null) return null; IEditorInput input= editor.getEditorInput(); if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); return manager.getWorkingCopy(input); } // will eventually be replaced by a method provided by jdt.core private IRegion selectWord(IDocument document, int anchor) { try { int offset= anchor; char c; while (offset >= 0) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; --offset; } int start= offset; offset= anchor; int length= document.getLength(); while (offset < length) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; ++offset; } int end= offset; if (start == end) return new Region(start, 0); else return new Region(start + 1, end - start - 1); } catch (BadLocationException x) { return null; } } IRegion getCurrentTextRegion(ISourceViewer viewer) { int offset= getCurrentTextOffset(viewer); if (offset == -1) return null; IJavaElement input= SelectionConverter.getInput(JavaEditor.this); if (input == null) return null; try { IJavaElement[] elements= ((ICodeAssist) input).codeSelect(offset, 0); if (elements == null || elements.length == 0) return null; return selectWord(viewer.getDocument(), offset); } catch (JavaModelException e) { return null; } } private int getCurrentTextOffset(ISourceViewer viewer) { try { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return -1; Display display= text.getDisplay(); Point absolutePosition= display.getCursorLocation(); Point relativePosition= text.toControl(absolutePosition); return text.getOffsetAtLocation(relativePosition) + viewer.getVisibleRegion().getOffset(); } catch (IllegalArgumentException e) { return -1; } } private void highlightRegion(ISourceViewer viewer, IRegion region) { if (region.equals(fActiveRegion)) return; repairRepresentation(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; // highlight region int offset= region.getOffset() - viewer.getVisibleRegion().getOffset(); int length= region.getLength(); StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset); Color foregroundColor= fColor; Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor); text.setStyleRange(styleRange); // underline text.redrawRange(offset, length, true); fActiveRegion= region; } private void activateCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); if (fCursor == null) fCursor= new Cursor(display, SWT.CURSOR_HAND); text.setCursor(fCursor); } private void resetCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); if (fDefaultCursor == null) fDefaultCursor= new Cursor(display, SWT.CURSOR_IBEAM); text.setCursor(fDefaultCursor); if (fCursor != null) { fCursor.dispose(); fCursor= null; } } /* * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) */ public void keyPressed(KeyEvent event) { if (fActive) { deactivate(); return; } if (event.keyCode != SWT.CTRL) { deactivate(); return; } fActive= true; ISourceViewer viewer= getSourceViewer(); if (viewer == null) return; IRegion region= getCurrentTextRegion(viewer); if (region == null) return; // removed for #25871 // highlightRegion(viewer, region); // activateCursor(viewer); } /* * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) */ public void keyReleased(KeyEvent event) { if (!fActive) return; deactivate(); } /* * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) */ public void mouseDoubleClick(MouseEvent e) {} /* * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) */ public void mouseDown(MouseEvent event) { if (!fActive) return; if (event.stateMask != SWT.CTRL) { deactivate(); return; } if (event.button != 1) { deactivate(); return; } } /* * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) */ public void mouseUp(MouseEvent e) { if (!fActive) return; if (e.button != 1) { deactivate(); return; } deactivate(); IAction action= getAction("OpenEditor"); //$NON-NLS-1$ if (action == null) return; action.run(); } /* * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) */ public void mouseMove(MouseEvent event) { if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) { deactivate(); return; } if (!fActive) { if (event.stateMask != SWT.CTRL) return; // Ctrl was already pressed fActive= true; } ISourceViewer viewer= getSourceViewer(); if (viewer == null) { deactivate(); return; } StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) { deactivate(); return; } if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) { deactivate(); return; } IRegion region= getCurrentTextRegion(viewer); if (region == null) { repairRepresentation(); return; } highlightRegion(viewer, region); activateCursor(viewer); } /* * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) */ public void focusGained(FocusEvent e) {} /* * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent event) { deactivate(); } /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { deactivate(); } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput == null) return; deactivate(); oldInput.removeDocumentListener(this); } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput == null) return; newInput.addDocumentListener(this); } /* * @see PaintListener#paintControl(PaintEvent) */ public void paintControl(PaintEvent event) { if (fActiveRegion == null) return; ISourceViewer viewer= getSourceViewer(); if (viewer == null) return; IRegion region= viewer.getVisibleRegion(); if (!includes(region, fActiveRegion)) return; StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; int offset= fActiveRegion.getOffset() - region.getOffset(); int length= fActiveRegion.getLength(); // support for bidi Point minLocation= getMinimumLocation(text, offset, length); Point maxLocation= getMaximumLocation(text, offset, length); int x1= minLocation.x; int x2= minLocation.x + maxLocation.x - minLocation.x - 1; int y= minLocation.y + text.getLineHeight() - 1; GC gc= event.gc; if (fColor != null && !fColor.isDisposed()) gc.setForeground(fColor); gc.drawLine(x1, y, x2, y); } private boolean includes(IRegion region, IRegion position) { return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); } private Point getMinimumLocation(StyledText text, int offset, int length) { Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x < minLocation.x) minLocation.x= location.x; if (location.y < minLocation.y) minLocation.y= location.y; } return minLocation; } private Point getMaximumLocation(StyledText text, int offset, int length) { Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x > maxLocation.x) maxLocation.x= location.x; if (location.y > maxLocation.y) maxLocation.y= location.y; } return maxLocation; } } /** * This action dispatches into two behaviours: If there is no current text * hover, the javadoc is displayed using information presenter. If there is * a current text hover, it is converted into a information presenter in * order to make it sticky. */ class InformationDispatchAction extends TextEditorAction { /** The wrapped text operation action. */ private final TextOperationAction fTextOperationAction; /** * Creates a dispatch action. */ public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) { super(resourceBundle, prefix, JavaEditor.this); if (textOperationAction == null) throw new IllegalArgumentException(); fTextOperationAction= textOperationAction; } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) { fTextOperationAction.run(); return; } if (! (sourceViewer instanceof ITextViewerExtension2)) { fTextOperationAction.run(); return; } ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer; // does a text hover exist? ITextHover textHover= textViewerExtension2.getCurrentTextHover(); if (textHover == null) { fTextOperationAction.run(); return; } Point hoverEventLocation= textViewerExtension2.getHoverEventLocation(); int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y); if (offset == -1) { fTextOperationAction.run(); return; } try { // get the text hover content IDocument document= sourceViewer.getDocument(); String contentType= document.getContentType(offset); final IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset); if (hoverRegion == null) return; final String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion); // with information provider IInformationProvider informationProvider= new IInformationProvider() { /* * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int) */ public IRegion getSubject(ITextViewer textViewer, int offset) { return hoverRegion; } /* * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) */ public String getInformation(ITextViewer textViewer, IRegion subject) { return hoverInfo; } }; fInformationPresenter.setOffset(offset); fInformationPresenter.setInformationProvider(informationProvider, contentType); fInformationPresenter.showInformation(); } catch (BadLocationException e) { } } // modified version from TextViewer private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { StyledText styledText= textViewer.getTextWidget(); IDocument document= textViewer.getDocument(); IRegion visibleRegion= textViewer.getVisibleRegion(); if (document == null) return -1; try { return styledText.getOffsetAtLocation(new Point(x, y)) + visibleRegion.getOffset(); } catch (IllegalArgumentException e) { return -1; } } } /** Preference key for showing the line number ruler */ private final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER; /** Preference key for the foreground color of the line numbers */ private final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR; /** Preference key for the link color */ private final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR; // /** Preference key for the default hover */ // private static final String DEFAULT_HOVER= PreferenceConstants.EDITOR_DEFAULT_HOVER; // /** Preference key for hover while no modifier is pressed */ // private static final String NONE_HOVER= PreferenceConstants.EDITOR_NONE_HOVER; // /** Preference key for hover while Ctrl modifier is pressed */ // private static final String CTRL_HOVER= PreferenceConstants.EDITOR_CTRL_HOVER; // /** Preference key for hover while Shift modifier is pressed */ // private static final String SHIFT_HOVER= PreferenceConstants.EDITOR_SHIFT_HOVER; // /** Preference key for hover while Ctrl+Alt modifiers are pressed */ // private static final String CTRL_ALT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_HOVER; // /** Preference key for hover while Ctrl+Alt+Shift modifiers are pressed */ // private static final String CTRL_ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER; // /** Preference key for hover while Ctrl+Shift modifiers are pressed */ // private static final String CTRL_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER; // /** Preference key for hover while Alt+Shift modifiers are pressed */ // private static final String ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_ALT_SHIFT_HOVER; // /** Id indicating no hover is configured */ // private static final String NO_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_NO_HOVER_CONFIGURED_ID; // /** Hover id indicating the default hover */ // private static final String DEFAULT_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID; /** The outline page */ protected JavaOutlinePage fOutlinePage; /** Outliner context menu Id */ protected String fOutlinerContextMenuId; /** The selection changed listener */ protected ISelectionChangedListener fSelectionChangedListener= new SelectionChangedListener(); /** The outline page selection updater */ private OutlinePageSelectionUpdater fUpdater; /** Indicates whether this editor should react on outline page selection changes */ private int fIgnoreOutlinePageSelection; /** The line number ruler column */ private LineNumberRulerColumn fLineNumberRulerColumn; /** This editor's encoding support */ private DefaultEncodingSupport fEncodingSupport; /** The mouse listener */ private MouseClickListener fMouseListener; /** The information presenter. */ private InformationPresenter fInformationPresenter; protected CompositeActionGroup fActionGroups; private CompositeActionGroup fContextMenuGroup; /** * Returns the most narrow java element including the given offset * * @param offset the offset inside of the requested element */ abstract protected IJavaElement getElementAt(int offset); /** * Returns the java element of this editor's input corresponding to the given IJavaElement */ abstract protected IJavaElement getCorrespondingElement(IJavaElement element); /** * Sets the input of the editor's outline page. */ abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input); /** * Default constructor. */ public JavaEditor() { super(); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this)); setRangeIndicator(new DefaultRangeIndicator()); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); if (JavaEditorPreferencePage.synchronizeOutlineOnCursorMove()) fUpdater= new OutlinePageSelectionUpdater(); } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { ISourceViewer viewer= createJavaSourceViewer(parent, ruler, styles); StyledText text= viewer.getTextWidget(); text.addBidiSegmentListener(new BidiSegmentListener() { public void lineGetSegments(BidiSegmentEvent event) { event.segments= getBidiLineSegments(event.lineOffset, event.lineText); } }); JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); return viewer; } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return super.createSourceViewer(parent, ruler, styles); } /* * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.affectsBehavior(event); } /** * Sets the outliner's context menu ID. */ protected void setOutlinerContextMenuId(String menuId) { fOutlinerContextMenuId= menuId; } /** * Returns the standard action group of this editor. */ protected ActionGroup getActionGroup() { return fActionGroups; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN)); menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW)); ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /** * Creates the outline page used with this editor. */ protected JavaOutlinePage createOutlinePage() { JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this); page.addSelectionChangedListener(fSelectionChangedListener); setOutlinePageInput(page, getEditorInput()); return page; } /** * Informs the editor that its outliner has been closed. */ public void outlinePageClosed() { if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage= null; resetHighlightRange(); } } /** * Synchronizes the outliner selection with the actual cursor * position in the editor. */ public void synchronizeOutlinePageSelection() { if (isEditingScriptRunning()) return; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null || fOutlinePage == null) return; StyledText styledText= sourceViewer.getTextWidget(); if (styledText == null) return; int offset= sourceViewer.getVisibleRegion().getOffset(); int caret= offset + styledText.getCaretOffset(); IJavaElement element= getElementAt(caret); if (element instanceof ISourceReference) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select((ISourceReference) element); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } } /* * Get the desktop's StatusLineManager */ protected IStatusLineManager getStatusLineManager() { IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) { return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); } return null; } /* * @see AbstractTextEditor#getAdapter(Class) */ public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { if (fOutlinePage == null) fOutlinePage= createOutlinePage(); return fOutlinePage; } if (IEncodingSupport.class.equals(required)) return fEncodingSupport; return super.getAdapter(required); } protected void setSelection(ISourceReference reference, boolean moveCursor) { ISelection selection= getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection= (TextSelection) selection; if (textSelection.getOffset() != 0 || textSelection.getLength() != 0) markInNavigationHistory(); } if (reference != null) { StyledText textWidget= null; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer != null) textWidget= sourceViewer.getTextWidget(); if (textWidget == null) return; try { ISourceRange range= reference.getSourceRange(); if (range == null) return; int offset= range.getOffset(); int length= range.getLength(); if (offset < 0 || length < 0) return; textWidget.setRedraw(false); setHighlightRange(offset, length, moveCursor); if (!moveCursor) return; offset= -1; length= -1; if (reference instanceof IMember) { range= ((IMember) reference).getNameRange(); if (range != null) { offset= range.getOffset(); length= range.getLength(); } } else if (reference instanceof IImportDeclaration) { String name= ((IImportDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); offset= range.getOffset() + content.indexOf(name); length= name.length(); } } else if (reference instanceof IPackageDeclaration) { String name= ((IPackageDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); offset= range.getOffset() + content.indexOf(name); length= name.length(); } } if (offset > -1 && length > 0) { sourceViewer.revealRange(offset, length); sourceViewer.setSelectedRange(offset, length); } } catch (JavaModelException x) { } catch (IllegalArgumentException x) { } finally { if (textWidget != null) textWidget.setRedraw(true); } } else if (moveCursor) { resetHighlightRange(); } markInNavigationHistory(); } public void setSelection(IJavaElement element) { if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) { /* * If the element is an ICompilationUnit this unit is either the input * of this editor or not being displayed. In both cases, nothing should * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) */ return; } IJavaElement corresponding= getCorrespondingElement(element); if (corresponding instanceof ISourceReference) { ISourceReference reference= (ISourceReference) corresponding; // set hightlight range setSelection(reference, true); // set outliner selection if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select(reference); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } } } public synchronized void editingScriptStarted() { ++ fIgnoreOutlinePageSelection; } public synchronized void editingScriptEnded() { -- fIgnoreOutlinePageSelection; } public synchronized boolean isEditingScriptRunning() { return (fIgnoreOutlinePageSelection > 0); } protected void doSelectionChanged(SelectionChangedEvent event) { ISourceReference reference= null; ISelection selection= event.getSelection(); Iterator iter= ((IStructuredSelection) selection).iterator(); while (iter.hasNext()) { Object o= iter.next(); if (o instanceof ISourceReference) { reference= (ISourceReference) o; break; } } if (!isActivePart() && JavaPlugin.getActivePage() != null) JavaPlugin.getActivePage().bringToTop(this); try { editingScriptStarted(); setSelection(reference, !isActivePart()); } finally { editingScriptEnded(); } } /* * @see AbstractTextEditor#adjustHighlightRange(int, int) */ protected void adjustHighlightRange(int offset, int length) { try { IJavaElement element= getElementAt(offset); while (element instanceof ISourceReference) { ISourceRange range= ((ISourceReference) element).getSourceRange(); if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) { setHighlightRange(range.getOffset(), range.getLength(), true); if (fOutlinePage != null) { fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); fOutlinePage.select((ISourceReference) element); fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); } return; } element= element.getParent(); } } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); } resetHighlightRange(); } protected boolean isActivePart() { IWorkbenchWindow window= getSite().getWorkbenchWindow(); IPartService service= window.getPartService(); IWorkbenchPart part= service.getActivePart(); return part != null && part.equals(this); } /* * @see StatusTextEditor#getStatusHeader(IStatus) */ protected String getStatusHeader(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusHeader(status); if (message != null) return message; } return super.getStatusHeader(status); } /* * @see StatusTextEditor#getStatusBanner(IStatus) */ protected String getStatusBanner(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusBanner(status); if (message != null) return message; } return super.getStatusBanner(status); } /* * @see StatusTextEditor#getStatusMessage(IStatus) */ protected String getStatusMessage(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusMessage(status); if (message != null) return message; } return super.getStatusMessage(status); } /* * @see AbstractTextEditor#doSetInput */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (fEncodingSupport != null) fEncodingSupport.reset(); setOutlinePageInput(fOutlinePage, input); } /* * @see IWorkbenchPart#dispose() */ public void dispose() { if (fMouseListener != null) { fMouseListener.uninstall(); fMouseListener= null; } if (fEncodingSupport != null) { fEncodingSupport.dispose(); fEncodingSupport= null; } super.dispose(); } protected void createActions() { super.createActions(); ResourceAction action= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK); setAction(ITextEditorActionConstants.ADD_TASK, action); ActionGroup oeg, ovg, sg, jsg; fActionGroups= new CompositeActionGroup(new ActionGroup[] { oeg= new OpenEditorActionGroup(this), ovg= new OpenViewActionGroup(this), sg= new ShowActionGroup(this), jsg= new JavaSearchActionGroup(this) }); fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg}); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ action= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) action); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC); setAction("ShowJavaDoc", action); //$NON-NLS-1$ fEncodingSupport= new DefaultEncodingSupport(); fEncodingSupport.initialize(this); if (fMouseListener == null) { fMouseListener= new MouseClickListener(); fMouseListener.install(); } } 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); } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; String property= event.getProperty(); if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) { Object value= event.getNewValue(); if (value instanceof Integer) { sourceViewer.getTextWidget().setTabs(((Integer) value).intValue()); } else if (value instanceof String) { sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value)); } return; } if (LINE_NUMBER_RULER.equals(property)) { if (isLineNumberRulerVisible()) showLineNumberRuler(); else hideLineNumberRuler(); return; } if (fLineNumberRulerColumn != null && (LINE_NUMBER_COLOR.equals(property) || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || PREFERENCE_COLOR_BACKGROUND.equals(property))) { initializeLineNumberRulerColumn(fLineNumberRulerColumn); } if (PreferenceConstants.EDITOR_SHOW_HOVER.equals(property)) { updateHoverBehavior(); } if (isJavaEditorHoverProperty(property)) { updateHoverBehavior(); } } finally { super.handlePreferenceStoreChanged(event); } } private boolean isJavaEditorHoverProperty(String property) { return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property) || PreferenceConstants.EDITOR_NONE_HOVER.equals(property) || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property) || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property) || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property) || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property) || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property) || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property); } /** * Shows the line number ruler column. */ private void showLineNumberRuler() { IVerticalRuler v= getVerticalRuler(); if (v instanceof CompositeRuler) { CompositeRuler c= (CompositeRuler) v; c.addDecorator(1, createLineNumberRulerColumn()); } } /** * Hides the line number ruler column. */ private void hideLineNumberRuler() { IVerticalRuler v= getVerticalRuler(); if (v instanceof CompositeRuler) { CompositeRuler c= (CompositeRuler) v; c.removeDecorator(1); } } /** * Return whether the line number ruler column should be * visible according to the preference store settings. * @return <code>true</code> if the line numbers should be visible */ private boolean isLineNumberRulerVisible() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(LINE_NUMBER_RULER); } /** * Returns a segmentation of the line of the given document appropriate for bidi rendering. * The default implementation returns only the string literals of a java code line as segments. * * @param document the document * @param lineOffset the offset of the line * @return the line's bidi segmentation * @throws BadLocationException in case lineOffset is not valid in document */ public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException { IRegion line= document.getLineInformationOfOffset(lineOffset); ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength()); List segmentation= new ArrayList(); for (int i= 0; i < linePartitioning.length; i++) { if (JavaPartitionScanner.JAVA_STRING.equals(linePartitioning[i].getType())) segmentation.add(linePartitioning[i]); } if (segmentation.size() == 0) return null; int size= segmentation.size(); int[] segments= new int[size * 2 + 1]; int j= 0; for (int i= 0; i < size; i++) { ITypedRegion segment= (ITypedRegion) segmentation.get(i); if (i == 0) segments[j++]= 0; int offset= segment.getOffset() - lineOffset; if (offset > segments[j - 1]) segments[j++]= offset; if (offset + segment.getLength() >= line.getLength()) break; segments[j++]= offset + segment.getLength(); } if (j < segments.length) { int[] result= new int[j]; System.arraycopy(segments, 0, result, 0, j); segments= result; } return segments; } /** * Returns a segmentation of the given line appropriate for bidi rendering. The default * implementation returns only the string literals of a java code line as segments. * * @param lineOffset the offset of the line * @param line the content of the line * @return the line's bidi segmentation */ protected int[] getBidiLineSegments(int lineOffset, String line) { IDocumentProvider provider= getDocumentProvider(); if (provider != null && line != null && line.length() > 0) { IDocument document= provider.getDocument(getEditorInput()); if (document != null) try { return getBidiLineSegments(document, lineOffset); } catch (BadLocationException x) { // ignore } } return null; } /* * @see AbstractTextEditor#handleCursorPositionChanged() */ protected void handleCursorPositionChanged() { super.handleCursorPositionChanged(); if (!isEditingScriptRunning() && fUpdater != null) fUpdater.post(); } /** * Initializes the given line number ruler column from the preference store. * @param rulerColumn the ruler column to be initialized */ protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); IColorManager manager= textTools.getColorManager(); IPreferenceStore store= getPreferenceStore(); if (store != null) { RGB rgb= null; // foreground color if (store.contains(LINE_NUMBER_COLOR)) { if (store.isDefault(LINE_NUMBER_COLOR)) rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR); else rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR); } rulerColumn.setForeground(manager.getColor(rgb)); rgb= null; // background color if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { if (store.contains(PREFERENCE_COLOR_BACKGROUND)) { if (store.isDefault(PREFERENCE_COLOR_BACKGROUND)) rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND); else rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND); } } rulerColumn.setBackground(manager.getColor(rgb)); } } /** * Creates a new line number ruler column that is appropriately initialized. */ protected IVerticalRulerColumn createLineNumberRulerColumn() { fLineNumberRulerColumn= new LineNumberRulerColumn(); initializeLineNumberRulerColumn(fLineNumberRulerColumn); return fLineNumberRulerColumn; } /* * @see AbstractTextEditor#createVerticalRuler() */ protected IVerticalRuler createVerticalRuler() { CompositeRuler ruler= new CompositeRuler(); ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH)); if (isLineNumberRulerVisible()) ruler.addDecorator(1, createLineNumberRulerColumn()); return ruler; } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() */ protected void updatePropertyDependentActions() { super.updatePropertyDependentActions(); if (fEncodingSupport != null) fEncodingSupport.reset(); } /* * Update the hovering behavior depending on the preferences. */ private void updateHoverBehavior() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(getSourceViewer()); for (int i= 0; i < types.length; i++) { String t= types[i]; int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension2) { if (stateMasks != null) { for (int j= 0; j < stateMasks.length; j++) { int stateMask= stateMasks[j]; ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover= configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } /* * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return getEditorInput().getAdapter(IJavaElement.class); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) */ protected void doSetSelection(ISelection selection) { super.doSetSelection(selection); synchronizeOutlinePageSelection(); } /* * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. * widgets.Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); ISourceViewer sourceViewer= getSourceViewer(); SourceViewerConfiguration sourceViewerConfiguration= getSourceViewerConfiguration(); IInformationControlCreator informationControlCreator= new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { boolean cutDown= false; int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown)); } }; fInformationPresenter= new InformationPresenter(informationControlCreator); fInformationPresenter.setSizeConstraints(60, 10, true, true); fInformationPresenter.install(sourceViewer); } }
26,262
Bug 26262 link hover - paints 'assert' blue
20021113 open junit Assert class hover over the 'assert' word in the following method (with ctrl pressed) static public void assert(String message, boolean condition) { if (!condition) fail(message); } note that 'assert' stays blue even after you move the mouse somewhere else (it does not seem to happen for any other word)
resolved fixed
758d8a8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-11-19T16:16:43Z
2002-11-14T10:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCodeScanner.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.rules.ICharacterScanner; import org.eclipse.jface.text.rules.IRule; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.IWordDetector; 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.jface.util.PropertyChangeEvent; import org.eclipse.jdt.core.JavaCore; 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 class VersionedWordRule extends WordRule { private final String fVersion; private final boolean fEnable; private String fCurrentVersion; public VersionedWordRule(IWordDetector detector, String version, boolean enable, String currentVersion) { super(detector); fVersion= version; fEnable= enable; fCurrentVersion= currentVersion; } public void setCurrentVersion(String version) { fCurrentVersion= version; } /* * @see IRule#evaluate */ public IToken evaluate(ICharacterScanner scanner) { IToken token= super.evaluate(scanner); if (fEnable) { if (fCurrentVersion.equals(fVersion)) return token; return Token.UNDEFINED; } else { if (fCurrentVersion.equals(fVersion)) return Token.UNDEFINED; return token; } } } private static final String SOURCE_VERSION= JavaCore.COMPILER_SOURCE; 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[] fgNewKeywords= { "assert" }; //$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 static String[] fgTokenProperties= { IJavaColorConstants.JAVA_KEYWORD, IJavaColorConstants.JAVA_STRING, IJavaColorConstants.JAVA_DEFAULT }; private VersionedWordRule fVersionedWordRule; /** * 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 character constants. Token token= getToken(IJavaColorConstants.JAVA_STRING); 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 new keywords, 4077 Object version= null; try { version= JavaCore.getOptions().get(SOURCE_VERSION); } catch (NullPointerException x) { // plugin not initialized - happens in test code } if (version instanceof String) { fVersionedWordRule= new VersionedWordRule(new JavaWordDetector(), "1.4", true, (String) version); //$NON-NLS-1$ token= getToken(IJavaColorConstants.JAVA_KEYWORD); for (int i=0; i<fgNewKeywords.length; i++) fVersionedWordRule.addWord(fgNewKeywords[i], token); rules.add(fVersionedWordRule); } // 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); 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; } /* * @see RuleBasedScanner#setRules(IRule[]) */ public void setRules(IRule[] rules) { int i; for (i= 0; i < rules.length; i++) if (rules[i].equals(fVersionedWordRule)) break; // not found - invalidate fVersionedWordRule if (i == rules.length) fVersionedWordRule= null; super.setRules(rules); } /* * @see AbstractJavaScanner#affectsBehavior(PropertyChangeEvent) */ public boolean affectsBehavior(PropertyChangeEvent event) { return event.getProperty().equals(SOURCE_VERSION) || super.affectsBehavior(event); } /* * @see AbstractJavaScanner#adaptToPreferenceChange(PropertyChangeEvent) */ public void adaptToPreferenceChange(PropertyChangeEvent event) { if (event.getProperty().equals(SOURCE_VERSION)) { Object value= event.getNewValue(); if (value instanceof String) { String s= (String) value; if (fVersionedWordRule != null) fVersionedWordRule.setCurrentVersion(s); } } else if (super.affectsBehavior(event)) { super.adaptToPreferenceChange(event); } } }