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
44,181
Bug 44181 Source->delegate works only for public methods [code manipulation]
Hi, Generate Delegate methods display only public methods for target class. For classes in the same package also default and protected methods should be shown. And for subclasses in other packages protected should be shown (I think more for completeness than for usefulness). Bye
resolved fixed
dd974de
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-07T14:35:30Z
2003-10-04T17:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddDelegateMethodsAction.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * Martin Moebius * *****************************************************************************/ package org.eclipse.jdt.ui.actions; import java.lang.reflect.InvocationTargetException; import java.text.Collator; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.Window; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.internal.corext.codemanipulation.AddDelegateMethodsOperation; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.AddDelegateMethodsOperation.Methods2Field; import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.ActionUtil; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.dialogs.SourceActionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.util.ElementValidator; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Creates delegate methods for a type's fields. Opens a dialog with a list of * fields for which delegate methods can be generated. User is able to check or * uncheck items before methods are generated. * <p> * Will open the parent compilation unit in a Java editor. The result is * unsaved, so the user can decide if the changes are acceptable. * <p> * The action is applicable to structured selections containing elements * of type <code>IField</code> or <code>IType</code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * Contributors: * Martin Moebius: [email protected] - bug: 28793 * @since 2.1 */ public class AddDelegateMethodsAction extends SelectionDispatchAction { private static final String DIALOG_TITLE = ActionMessages.getString("AddDelegateMethodsAction.error.title"); //$NON-NLS-1$ private CompilationUnitEditor fEditor; /** * Creates a new <code>AddDelegateMethodsAction</code>. The action requires * that the selection provided by the site's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param site the site providing context information for this action */ public AddDelegateMethodsAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("AddDelegateMethodsAction.label")); //$NON-NLS-1$ setDescription(ActionMessages.getString("AddDelegateMethodsAction.description")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("AddDelegateMethodsAction.tooltip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_DELEGATE_METHODS_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public AddDelegateMethodsAction(CompilationUnitEditor editor) { this(editor.getEditorSite()); fEditor = editor; setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null); } //---- Structured Viewer ----------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void selectionChanged(IStructuredSelection selection) { try { setEnabled(canEnable(selection)); } catch (JavaModelException e) { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 if (JavaModelUtil.filterNotPresentException(e)) JavaPlugin.log(e); setEnabled(false); } } private boolean canEnable(IStructuredSelection selection) throws JavaModelException { if (getSelectedFields(selection) != null) return true; if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) { IType type= (IType) selection.getFirstElement(); return type.getCompilationUnit() != null && type.isClass(); // look if class: not cheap but done by all source generation actions } if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit)) return true; return false; } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void run(IStructuredSelection selection) { try { IField[] selectedFields = getSelectedFields(selection); if (canRunOn(selectedFields)) { run(selectedFields[0].getDeclaringType(), selectedFields, false); return; } Object firstElement = selection.getFirstElement(); if (firstElement instanceof IType) run((IType) firstElement, new IField[0], false); else if (firstElement instanceof ICompilationUnit) run(JavaElementUtil.getMainType((ICompilationUnit) firstElement), new IField[0], false); else MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.not_applicable")); //$NON-NLS-1$ } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } } private static boolean canRunOn(IType type) throws JavaModelException { if (type == null || type.getCompilationUnit() == null || type.isInterface()) return false; return canRunOn(type.getFields()); } private static boolean canRunOn(IField[] fields) throws JavaModelException { if (fields == null) { return false; } int count = 0; for (int i = 0; i < fields.length; i++) { if (!hasPrimitiveType(fields[i]) || isArray(fields[i])) { count++; } } return (count > 0); } /* * Returns fields in the selection or <code>null</code> if the selection is * empty or not valid. */ private IField[] getSelectedFields(IStructuredSelection selection) { List elements = selection.toList(); int nElements = elements.size(); if (nElements > 0) { IField[] res = new IField[nElements]; ICompilationUnit cu = null; for (int i = 0; i < nElements; i++) { Object curr = elements.get(i); if (curr instanceof IField) { IField fld = (IField) curr; if (i == 0) { // remember the cu of the first element cu = fld.getCompilationUnit(); if (cu == null) { return null; } } else if (!cu.equals(fld.getCompilationUnit())) { // all fields must be in the same CU return null; } try { if (fld.getDeclaringType().isInterface()) { // no delegates for fields in interfaces or fields with return null; } } catch (JavaModelException e) { JavaPlugin.log(e); return null; } res[i] = fld; } else { return null; } } return res; } return null; } private void run(IType type, IField[] preselected, boolean editor) throws CoreException { if (!ElementValidator.check(type, getShell(), DIALOG_TITLE, editor)) return; if (!ActionUtil.isProcessable(getShell(), type)) return; if(!canRunOn(type)){ MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.not_applicable")); //$NON-NLS-1$ return; } showUI(type, preselected); } //---- Java Editior -------------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void selectionChanged(ITextSelection selection) { } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void run(ITextSelection selection) { try { IJavaElement input= SelectionConverter.getInput(fEditor); if (!ActionUtil.isProcessable(getShell(), input)) return; IJavaElement[] elements = SelectionConverter.codeResolve(fEditor); if (elements.length == 1 && (elements[0] instanceof IField)) { IField field = (IField) elements[0]; run(field.getDeclaringType(), new IField[] { field }, true); return; } IJavaElement element = SelectionConverter.getElementAtOffset(fEditor); if (element != null) { IType type = (IType) element.getAncestor(IJavaElement.TYPE); if (type != null) { if (type.getFields().length > 0) { run(type, new IField[0], true); return; } } } MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.not_applicable")); //$NON-NLS-1$ } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } } //---- Helpers ------------------------------------------------------------------- private static class AddDelegateMethodsActionStatusValidator implements ISelectionStatusValidator { private static int fEntries; AddDelegateMethodsActionStatusValidator(int entries) { fEntries= entries; } public IStatus validate(Object[] selection) { StatusInfo state = new StatusInfo(); if (selection != null && selection.length > 0) { HashSet map = new HashSet(selection.length); int count = 0; for (int i = 0; i < selection.length; i++) { Object key = selection[i]; if (selection[i] instanceof Methods2Field) { count++; try { key = createSignatureKey(((Methods2Field) selection[i]).fMethod); } catch (JavaModelException e) { return new StatusInfo(IStatus.ERROR, e.toString()); } } if (!map.add(key)) { //$NON-NLS-1$ state = new StatusInfo(IStatus.ERROR, ActionMessages.getString("AddDelegateMethodsAction.duplicate_methods")); //$NON-NLS-1$ break; } else { String message; message = ActionMessages.getFormattedString("AddDelegateMethodsAction.selectioninfo.more", //$NON-NLS-1$ new Object[] { String.valueOf(count), String.valueOf(fEntries)} ); state = new StatusInfo(IStatus.INFO, message); } } } else return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$ return state; } } private static ISelectionStatusValidator createValidator(int entries) { AddDelegateMethodsActionStatusValidator validator= new AddDelegateMethodsActionStatusValidator(entries); return validator; } private void showUI(IType type, IField[] preselected) { try { AddDelegateMethodsContentProvider provider = new AddDelegateMethodsContentProvider(type); Methods2FieldLabelProvider methodLabel = new Methods2FieldLabelProvider(); SourceActionDialog dialog = new SourceActionDialog(getShell(), methodLabel, provider, fEditor, type); dialog.setValidator(createValidator(provider.getNumEntries())); Methods2FieldSorter sorter= new Methods2FieldSorter(); dialog.setSorter(sorter); dialog.setInput(new Object()); dialog.setContainerMode(true); dialog.setMessage(ActionMessages.getString("AddDelegateMethodsAction.message")); //$NON-NLS-1$ dialog.setTitle(ActionMessages.getString("AddDelegateMethodsAction.title")); //$NON-NLS-1$ Object[] elements= provider.getElements(null); sorter.sort(null, elements); Object[] expand= {elements[0]}; dialog.setExpandedElements(expand); dialog.setInitialSelections(preselected); dialog.setSize(60, 18); int result = dialog.open(); if (result == Window.OK) { Object[] o = dialog.getResult(); if (o == null) return; ArrayList methods = new ArrayList(o.length); for (int i = 0; i < o.length; i++) { if (o[i] instanceof Methods2Field) methods.add(o[i]); } IEditorPart part = EditorUtility.openInEditor(type); type = (IType) JavaModelUtil.toWorkingCopy(type); IRewriteTarget target= (IRewriteTarget) part.getAdapter(IRewriteTarget.class); IMethod[] createdMethods= null; try { if (target != null) { target.beginCompoundChange(); } // pass dialog based information to the operation IJavaElement elementPosition= dialog.getElementPosition(); if (elementPosition != null) elementPosition= JavaModelUtil.toWorkingCopy(elementPosition); CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(); settings.createComments= dialog.getGenerateComment(); createdMethods= processResults(methods, type, elementPosition, settings); } finally { if (target != null) { target.endCompoundChange(); } } if (createdMethods != null && createdMethods.length > 0) { synchronized (type.getCompilationUnit()) { type.getCompilationUnit().reconcile(); } EditorUtility.revealInEditor(part, createdMethods[0]); } } } catch (CoreException e) { ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } catch (InvocationTargetException e) { ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } } /**creates methods in class*/ private IMethod[] processResults(List list, IType type, IJavaElement elementPosition, CodeGenerationSettings settings) throws InvocationTargetException { if (list.size() == 0) return null; AddDelegateMethodsOperation op = new AddDelegateMethodsOperation(list, settings, type, elementPosition); IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow(); if (context == null) { context= new BusyIndicatorRunnableContext(); } try { context.run(false, true, new WorkbenchRunnableAdapter(op)); } catch (InterruptedException e) { // cancel pressed return null; } return op.getCreatedMethods(); } /** The model (content provider) for the field-methods tree */ private static class AddDelegateMethodsContentProvider implements ITreeContentProvider { private Map fTreeMap= null; private Map fFieldMap= null; private Map fFilter= null; private int fNumEntries; /** * Method FieldContentProvider. * @param type outer type to insert in (hide final methods in tree)) */ AddDelegateMethodsContentProvider(IType type) throws JavaModelException { fFilter= new HashMap(); //hiding final methods fTreeMap= new TreeMap(); //mapping name to methods fFieldMap= new HashMap(); //mapping name to field fNumEntries= buildModel(type); } public int getNumEntries() { return fNumEntries; } /* Builds the entry list for the tree, and returns the number of entries in it */ private int buildModel(IType type) throws JavaModelException { int numEntries= 0; IField[] fields = type.getFields(); //build map to filter against IMethod[] finMeths = resolveFinalMethods(type); for (int i = 0; i < finMeths.length; i++) { fFilter.put(createSignatureKey(finMeths[i]), finMeths[i]); } IMethod[] filter = type.getMethods(); for (int i = 0; i < filter.length; i++) { fFilter.put(createSignatureKey(filter[i]), filter[i]); } for (int i = 0; i < fields.length; i++) { IType fieldType = resolveTypeOfField(fields[i]); if (fieldType == null) continue; IMethod[] methods = resolveMethodsHierarchy(fieldType); List accessMethods = new ArrayList(); //show public methods; hide constructors + final methods for (int j = 0; j < methods.length; j++) { boolean publicField = JdtFlags.isPublic(methods[j]); boolean constructor = methods[j].isConstructor(); boolean finalExist = fFilter.get(createSignatureKey(methods[j])) != null; if (publicField && !constructor && !finalExist) { accessMethods.add(new Methods2Field(methods[j], fields[i])); numEntries++; } } Object[] m = accessMethods.toArray(); Methods2Field[] mf = new Methods2Field[m.length]; for (int j = 0; j < m.length; j++) { mf[j] = (Methods2Field) m[j]; } fTreeMap.put(fields[i].getElementName(), mf); fFieldMap.put(fields[i].getElementName(), fields[i]); } return numEntries; } public Object[] getChildren(Object parentElement) { if (parentElement instanceof IField) { return (Object[]) fTreeMap.get(((IField) parentElement).getElementName()); } return null; } public Object getParent(Object element) { return null; } public boolean hasChildren(Object element) { return element instanceof IField; } public Object[] getElements(Object inputElement) { Object[] o = fTreeMap.keySet().toArray(); Object[] fields = new Object[o.length]; for (int i = 0; i < o.length; i++) { fields[i] = fFieldMap.get(o[i]); } return fields; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } /**just to wrap JavaElementLabelProvider using my Methods2Field*/ private static class Methods2FieldLabelProvider implements ILabelProvider { /**Delegate to forward calls*/ JavaElementLabelProvider fMethodLabel = null; public Methods2FieldLabelProvider() { fMethodLabel = new JavaElementLabelProvider(); fMethodLabel.turnOn(JavaElementLabelProvider.SHOW_TYPE); } public Image getImage(Object element) { if (element instanceof Methods2Field) { Methods2Field wrapper = (Methods2Field) element; return fMethodLabel.getImage(wrapper.fMethod); } else if (element instanceof IJavaElement) { return fMethodLabel.getImage(element); } return null; } public String getText(Object element) { if (element instanceof Methods2Field) { Methods2Field wrapper = (Methods2Field) element; return fMethodLabel.getText(wrapper.fMethod); } else if (element instanceof IJavaElement) { return fMethodLabel.getText(element); } return null; } public void addListener(ILabelProviderListener listener) { fMethodLabel.addListener(listener); } public void dispose() { fMethodLabel.dispose(); } public boolean isLabelProperty(Object element, String property) { return fMethodLabel.isLabelProperty(element, property); } public void removeListener(ILabelProviderListener listener) { fMethodLabel.removeListener(listener); } } /** and a delegate for the sorter*/ private static class Methods2FieldSorter extends ViewerSorter { JavaElementSorter fSorter = new JavaElementSorter(); public int category(Object element) { if (element instanceof Methods2Field) element = ((Methods2Field) element).fMethod; return fSorter.category(element); } public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof Methods2Field) e1 = ((Methods2Field) e1).fMethod; if (e2 instanceof Methods2Field) e2 = ((Methods2Field) e2).fMethod; return fSorter.compare(viewer, e1, e2); } public Collator getCollator() { return fSorter.getCollator(); } } /**return all methods of all super types, minus dups*/ private static IMethod[] resolveMethodsHierarchy(IType type) throws JavaModelException { Map map = new HashMap(); IType[] superTypes = JavaModelUtil.getAllSuperTypes(type, new NullProgressMonitor()); addMethodsToMapping(map, type); for (int i = 0; i < superTypes.length; i++) { addMethodsToMapping(map, superTypes[i]); } return (IMethod[]) map.values().toArray(new IMethod[map.values().size()]); } private static void addMethodsToMapping(Map map, IType type) throws JavaModelException { IMethod[] methods = type.getMethods(); for (int i = 0; i < methods.length; i++) { map.put(createSignatureKey(methods[i]), methods[i]); } } /**returns a non null array of final methods of the type*/ private static IMethod[] resolveFinalMethods(IType type) throws JavaModelException { //Interfaces are java.lang.Objects if (type.isInterface()) { type = getJavaLangObject(type.getJavaProject());//$NON-NLS-1$ } IMethod[] methods = resolveMethodsHierarchy(type); List list = new ArrayList(methods.length); for (int i = 0; i < methods.length; i++) { boolean isFinal = Flags.isFinal(methods[i].getFlags()); if (isFinal) list.add(methods[i]); } return (IMethod[]) list.toArray(new IMethod[list.size()]); } /**creates a key used for hashmaps for a method signature (name+arguments(fqn))*/ private static String createSignatureKey(IMethod method) throws JavaModelException { StringBuffer buffer = new StringBuffer(); buffer.append(method.getElementName()); String[] args = method.getParameterTypes(); for (int i = 0; i < args.length; i++) { String signature; if (isUnresolved(args[i])) { int acount = Signature.getArrayCount(args[i]); if (acount > 0) { String arg = args[i]; int index = arg.lastIndexOf(Signature.C_ARRAY); arg = arg.substring(index + 1); signature = Signature.toString(arg); } else { signature = Signature.toString(args[i]); } String[][] fqn = method.getDeclaringType().resolveType(signature); if (fqn != null) { buffer.append(fqn[0][0]).append('.').append(fqn[0][1]); //TODO check for [][] for (int j = 0; j < acount; j++) { buffer.append("[]"); //$NON-NLS-1$ } } }else{ signature=Signature.toString(args[i]); buffer.append(signature); } } return buffer.toString(); } private static boolean isUnresolved(String signature) { boolean flag = false; char c=Signature.getElementType(signature).charAt(0); boolean primitive=(c!= Signature.C_RESOLVED && c != Signature.C_UNRESOLVED); if(primitive) return flag; int acount = Signature.getArrayCount(signature); if (acount > 0) { int index = signature.lastIndexOf(Signature.C_ARRAY); c = signature.charAt(index + 1); } else { c = signature.charAt(0); } switch (c) { case Signature.C_RESOLVED : flag=false; break; case Signature.C_UNRESOLVED : flag=true; break; default : throw new IllegalArgumentException(); } return flag; } private static boolean hasPrimitiveType(IField field) throws JavaModelException { String signature = field.getTypeSignature(); char first = Signature.getElementType(signature).charAt(0); return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); } /** * returns Type of field. * * if field is primitve null is returned. * if field is array java.lang.Object is returned. **/ private static IType resolveTypeOfField(IField field) throws JavaModelException { boolean isPrimitive = hasPrimitiveType(field); boolean isArray = isArray(field); if (!isPrimitive && !isArray) { String typeName = JavaModelUtil.getResolvedTypeName(field.getTypeSignature(), field.getDeclaringType()); //if the cu has errors its possible no type name is resolved return typeName != null ? field.getJavaProject().findType(typeName) : null; } else if (isArray) { return getJavaLangObject(field.getJavaProject()); } return null; } private static IType getJavaLangObject(IJavaProject project) throws JavaModelException { return JavaModelUtil.findType(project, "java.lang.Object");//$NON-NLS-1$ } private static boolean isArray(IField field) throws JavaModelException { return Signature.getArrayCount(field.getTypeSignature()) > 0; } }
44,308
Bug 44308 NullPointerException when searching jars
I did a java search (ctrl-h) for references to "String". The search failed with this exception in the log: at org.eclipse.jdt.internal.ui.search.JavaSearchResultCollector.accept(JavaSearchResultCollector.java:121) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.report(MatchLocator.java:921) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.report(MatchLocator.java:914) at org.eclipse.jdt.internal.core.search.matching.PatternLocator.matchReportReference(PatternLocator.java:195) at org.eclipse.jdt.internal.core.search.matching.TypeReferenceLocator.matchReportReference(TypeReferenceLocator.java:178) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1122) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1297) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1308) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1183) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.process(MatchLocator.java:855) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:588) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:625) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:712) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:568) at org.eclipse.jdt.internal.ui.search.JavaSearchOperation.execute(JavaSearchOperation.java:98) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run(WorkspaceModifyOperation.java:71) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1555) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1572) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:85) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:101) There are two things wrong here: 1) We should make sure that we handle null "enclosingElements" in our search result acceptor (at least not NPE). The API clearly says we have to handle the case. 2) I haven't seen this behaviour from the java model before. What's the change, and why. Note that the reference that's being reported is in the package declaration of a binary type (in an external jar).
verified fixed
1e32b48
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-07T15:02:54Z
2003-10-07T15:20:00Z
org.eclipse.jdt.ui/ui
44,308
Bug 44308 NullPointerException when searching jars
I did a java search (ctrl-h) for references to "String". The search failed with this exception in the log: at org.eclipse.jdt.internal.ui.search.JavaSearchResultCollector.accept(JavaSearchResultCollector.java:121) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.report(MatchLocator.java:921) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.report(MatchLocator.java:914) at org.eclipse.jdt.internal.core.search.matching.PatternLocator.matchReportReference(PatternLocator.java:195) at org.eclipse.jdt.internal.core.search.matching.TypeReferenceLocator.matchReportReference(TypeReferenceLocator.java:178) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1122) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1297) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1308) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1183) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.process(MatchLocator.java:855) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:588) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:625) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:712) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:568) at org.eclipse.jdt.internal.ui.search.JavaSearchOperation.execute(JavaSearchOperation.java:98) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run(WorkspaceModifyOperation.java:71) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1555) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1572) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:85) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:101) There are two things wrong here: 1) We should make sure that we handle null "enclosingElements" in our search result acceptor (at least not NPE). The API clearly says we have to handle the case. 2) I haven't seen this behaviour from the java model before. What's the change, and why. Note that the reference that's being reported is in the package declaration of a binary type (in an external jar).
verified fixed
1e32b48
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-07T15:02:54Z
2003-10-07T15:20:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/search/NLSSearchResultCollector.java
44,308
Bug 44308 NullPointerException when searching jars
I did a java search (ctrl-h) for references to "String". The search failed with this exception in the log: at org.eclipse.jdt.internal.ui.search.JavaSearchResultCollector.accept(JavaSearchResultCollector.java:121) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.report(MatchLocator.java:921) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.report(MatchLocator.java:914) at org.eclipse.jdt.internal.core.search.matching.PatternLocator.matchReportReference(PatternLocator.java:195) at org.eclipse.jdt.internal.core.search.matching.TypeReferenceLocator.matchReportReference(TypeReferenceLocator.java:178) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1122) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1297) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1308) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.reportMatching(MatchLocator.java:1183) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.process(MatchLocator.java:855) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:588) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:625) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:712) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:568) at org.eclipse.jdt.internal.ui.search.JavaSearchOperation.execute(JavaSearchOperation.java:98) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run(WorkspaceModifyOperation.java:71) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1555) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1572) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:85) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:101) There are two things wrong here: 1) We should make sure that we handle null "enclosingElements" in our search result acceptor (at least not NPE). The API clearly says we have to handle the case. 2) I haven't seen this behaviour from the java model before. What's the change, and why. Note that the reference that's being reported is in the package declaration of a binary type (in an external jar).
verified fixed
1e32b48
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-07T15:02:54Z
2003-10-07T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultCollector.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import java.util.HashMap; 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.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.search.ui.IActionGroupFactory; import org.eclipse.search.ui.ISearchResultView; import org.eclipse.search.ui.SearchUI; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.search.IJavaSearchResultCollector; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog; public class JavaSearchResultCollector implements IJavaSearchResultCollector { private static final String MATCH= SearchMessages.getString("SearchResultCollector.match"); //$NON-NLS-1$ private static final String MATCHES= SearchMessages.getString("SearchResultCollector.matches"); //$NON-NLS-1$ private static final String DONE= SearchMessages.getString("SearchResultCollector.done"); //$NON-NLS-1$ private static final String SEARCHING= SearchMessages.getString("SearchResultCollector.searching"); //$NON-NLS-1$ private static final Boolean POTENTIAL_MATCH_VALUE= new Boolean(true); private static final String POTENTIAL_MATCH_DIALOG_ID= "Search.PotentialMatchDialog"; //$NON-NLS-1$ private IProgressMonitor fMonitor; private ISearchResultView fView; private JavaSearchOperation fOperation; private int fMatchCount= 0; private int fPotentialMatchCount= 0; private long fLastUpdateTime; private Integer[] fMessageFormatArgs= new Integer[1]; private class ActionGroupFactory implements IActionGroupFactory { public ActionGroup createActionGroup(ISearchResultView part) { return new SearchViewActionGroup(part); } } public JavaSearchResultCollector() { // This ensures that the image class is loaded correctly JavaPlugin.getDefault().getImageRegistry(); } /** * @see IJavaSearchResultCollector#aboutToStart(). */ public void aboutToStart() { fPotentialMatchCount= 0; fView= SearchUI.getSearchResultView(); fMatchCount= 0; fLastUpdateTime= 0; if (fView != null) { fView.searchStarted( new ActionGroupFactory(), fOperation.getSingularLabel(), fOperation.getPluralLabelPattern(), fOperation.getImageDescriptor(), JavaSearchPage.EXTENSION_POINT_ID, new JavaSearchResultLabelProvider(), new GotoMarkerAction(), new GroupByKeyComputer(), fOperation); } if (!getProgressMonitor().isCanceled()) getProgressMonitor().subTask(SEARCHING); } /** * @see IJavaSearchResultCollector#accept */ public void accept(IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy) throws CoreException { if (accuracy == POTENTIAL_MATCH && SearchUI.arePotentialMatchesIgnored()) return; IMarker marker= resource.createMarker(SearchUI.SEARCH_MARKER); HashMap attributes; Object groupKey= enclosingElement; attributes= new HashMap(7); if (accuracy == POTENTIAL_MATCH) { fPotentialMatchCount++; attributes.put(SearchUI.POTENTIAL_MATCH, POTENTIAL_MATCH_VALUE); if (groupKey == null) groupKey= "?:null"; //$NON-NLS-1$ else groupKey= "?:" + enclosingElement.getHandleIdentifier(); //$NON-NLS-1$ } ICompilationUnit cu= SearchUtil.findCompilationUnit(enclosingElement); if (cu != null && cu.isWorkingCopy()) attributes.put(IJavaSearchUIConstants.ATT_IS_WORKING_COPY, new Boolean(true)); //$NON-NLS-1$ JavaCore.addJavaElementMarkerAttributes(attributes, enclosingElement); attributes.put(IJavaSearchUIConstants.ATT_JE_HANDLE_ID, enclosingElement.getHandleIdentifier()); attributes.put(IMarker.CHAR_START, new Integer(Math.max(start, 0))); attributes.put(IMarker.CHAR_END, new Integer(Math.max(end, 0))); if (enclosingElement instanceof IMember && ((IMember)enclosingElement).isBinary()) attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CF_EDITOR); else attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CU_EDITOR); marker.setAttributes(attributes); fView.addMatch(enclosingElement.getElementName(), groupKey, resource, marker); fMatchCount++; if (!getProgressMonitor().isCanceled() && System.currentTimeMillis() - fLastUpdateTime > 1000) { getProgressMonitor().subTask(getFormattedMatchesString(fMatchCount)); fLastUpdateTime= System.currentTimeMillis(); } } /** * @see IJavaSearchResultCollector#done(). */ public void done() { if (!getProgressMonitor().isCanceled()) { String matchesString= getFormattedMatchesString(fMatchCount); getProgressMonitor().setTaskName(MessageFormat.format(DONE, new String[]{matchesString})); } if (fView != null) { if (fPotentialMatchCount > 0) explainPotentialMatch(fPotentialMatchCount); fView.searchFinished(); } // Cut no longer unused references because the collector might be re-used fView= null; fMonitor= null; } private void explainPotentialMatch(final int potentialMatchCount) { // Make sure we are doing it in the right thread. final Shell shell= fView.getSite().getShell(); final String title; if (potentialMatchCount == 1) title= new String(SearchMessages.getString("Search.potentialMatchDialog.title.foundPotentialMatch")); //$NON-NLS-1$ else title= new String(SearchMessages.getFormattedString("Search.potentialMatchDialog.title.foundPotentialMatches", "" + potentialMatchCount)); //$NON-NLS-1$ //$NON-NLS-2$ shell.getDisplay().syncExec(new Runnable() { public void run() { OptionalMessageDialog.open( POTENTIAL_MATCH_DIALOG_ID, //$NON-NLS-1$, shell, title, null, SearchMessages.getString("Search.potentialMatchDialog.message"), //$NON-NLS-1$, MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); } }); } /* * @see IJavaSearchResultCollector#getProgressMonitor(). */ public IProgressMonitor getProgressMonitor() { return fMonitor; } void setProgressMonitor(IProgressMonitor pm) { fMonitor= pm; } void setOperation(JavaSearchOperation operation) { fOperation= operation; } private String getFormattedMatchesString(int count) { if (fMatchCount == 1) return MATCH; fMessageFormatArgs[0]= new Integer(count); return MessageFormat.format(MATCHES, fMessageFormatArgs); } }
42,655
Bug 42655 SourceAttachmentBlock does not use dialog font for all widgets [dialogs] [build path]
null
resolved fixed
70b3510
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-07T17:46:33Z
2003-09-06T01:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.ClasspathContainerInitializer; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; /** * UI to set the source attachment archive and root. * Same implementation for both setting attachments for libraries from * variable entries and for normal (internal or external) jar. */ public class SourceAttachmentBlock { private static class UpdatedClasspathContainer implements IClasspathContainer { private IClasspathEntry[] fNewEntries; private IClasspathContainer fOriginal; public UpdatedClasspathContainer(IClasspathContainer original, IClasspathEntry[] newEntries) { fNewEntries= newEntries; fOriginal= original; } public IClasspathEntry[] getClasspathEntries() { return fNewEntries; } public String getDescription() { return fOriginal.getDescription(); } public int getKind() { return fOriginal.getKind(); } public IPath getPath() { return fOriginal.getPath(); } } private IStatusChangeListener fContext; private StringButtonDialogField fFileNameField; private SelectionButtonDialogField fWorkspaceButton; private SelectionButtonDialogField fExternalFolderButton; private IStatus fNameStatus; /** * The path to which the archive variable points. * Null if invalid path or not resolvable. Must not exist. */ private IPath fFileVariablePath; private IWorkspaceRoot fWorkspaceRoot; private Control fSWTWidget; private CLabel fFullPathResolvedLabel; private IJavaProject fProject; private IClasspathEntry fEntry; private IPath fContainerPath; /** * @deprecated */ public SourceAttachmentBlock(IWorkspaceRoot root, IStatusChangeListener context, IClasspathEntry oldEntry) { this(context, oldEntry, null, null); } /** * @param context listeners for status updates * @param entryToEdit The entry to edit * @param containerPath Path of the container that contains the given entry or * <code>null</code> if the entry does not belong to a container. * @param project Project to which the entry belongs. Can be * <code>null</code> if <code>getRunnable</code> is not run and the entry * does not belong to a container. * */ public SourceAttachmentBlock(IStatusChangeListener context, IClasspathEntry entry, IPath containerPath, IJavaProject project) { Assert.isNotNull(entry); fContext= context; fEntry= entry; fContainerPath= containerPath; fProject= project; int kind= entry.getEntryKind(); Assert.isTrue(kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE); fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); fNameStatus= new StatusInfo(); SourceAttachmentAdapter adapter= new SourceAttachmentAdapter(); // create the dialog fields (no widgets yet) if (isVariableEntry()) { fFileNameField= new VariablePathDialogField(adapter); fFileNameField.setDialogFieldListener(adapter); fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.varlabel")); //$NON-NLS-1$ fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.varbutton")); //$NON-NLS-1$ ((VariablePathDialogField)fFileNameField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.variable.button")); //$NON-NLS-1$ } else { fFileNameField= new StringButtonDialogField(adapter); fFileNameField.setDialogFieldListener(adapter); fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.label")); //$NON-NLS-1$ fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.externalfile.button")); //$NON-NLS-1$ fWorkspaceButton= new SelectionButtonDialogField(SWT.PUSH); fWorkspaceButton.setDialogFieldListener(adapter); fWorkspaceButton.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.internal.button")); //$NON-NLS-1$ fExternalFolderButton= new SelectionButtonDialogField(SWT.PUSH); fExternalFolderButton.setDialogFieldListener(adapter); fExternalFolderButton.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.externalfolder.button")); //$NON-NLS-1$ } // set the old settings setDefaults(); } public void setDefaults() { if (fEntry.getSourceAttachmentPath() != null) { fFileNameField.setText(fEntry.getSourceAttachmentPath().toString()); } else { fFileNameField.setText(""); //$NON-NLS-1$ } } private boolean isVariableEntry() { return fEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE; } /** * Gets the source attachment path chosen by the user */ public IPath getSourceAttachmentPath() { if (fFileNameField.getText().length() == 0) { return null; } return new Path(fFileNameField.getText()); } /** * Gets the source attachment root chosen by the user * Returns null to let JCore automatically detect the root. */ public IPath getSourceAttachmentRootPath() { return null; } /** * Creates the control */ public Control createControl(Composite parent) { PixelConverter converter= new PixelConverter(parent); fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 4; composite.setLayout(layout); if (isVariableEntry()) { int widthHint= converter.convertWidthInCharsToPixels(50); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 4; Label message= new Label(composite, SWT.LEFT); message.setLayoutData(gd); message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fEntry.getPath().lastSegment())); //$NON-NLS-1$ DialogField.createEmptySpace(composite, 1); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= widthHint; gd.horizontalSpan= 2; Label desc= new Label(composite, SWT.LEFT + SWT.WRAP); desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.filename.description")); //$NON-NLS-1$ desc.setLayoutData(gd); DialogField.createEmptySpace(composite, 1); fFileNameField.doFillIntoGrid(composite, 4); LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint); // label that shows the resolved path for variable jars DialogField.createEmptySpace(composite, 1); fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT); fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); fFullPathResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(composite, 2); LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null)); } else { int widthHint= converter.convertWidthInCharsToPixels(60); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 3; Label message= new Label(composite, SWT.LEFT); message.setLayoutData(gd); message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fEntry.getPath().lastSegment())); //$NON-NLS-1$ fWorkspaceButton.doFillIntoGrid(composite, 1); // archive name field fFileNameField.doFillIntoGrid(composite, 4); LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint); LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null)); // aditional 'browse workspace' button for normal jars DialogField.createEmptySpace(composite, 3); fExternalFolderButton.doFillIntoGrid(composite, 1); } fFileNameField.postSetFocusOnDialogField(parent.getDisplay()); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK); return composite; } private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { attachmentChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { attachmentDialogFieldChanged(field); } } private void attachmentChangeControlPressed(DialogField field) { if (field == fFileNameField) { IPath jarFilePath= isVariableEntry() ? chooseExtension() : chooseExtJarFile(); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } } } // ---------- IDialogFieldListener -------- private void attachmentDialogFieldChanged(DialogField field) { if (field == fFileNameField) { fNameStatus= updateFileNameStatus(); } else if (field == fWorkspaceButton) { IPath jarFilePath= chooseInternalJarFile(); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } return; } else if (field == fExternalFolderButton) { IPath folderPath= chooseExtFolder(); if (folderPath != null) { fFileNameField.setText(folderPath.toString()); } return; } doStatusLineUpdate(); } private void doStatusLineUpdate() { fFileNameField.enableButton(canBrowseFileName()); // set the resolved path for variable jars if (fFullPathResolvedLabel != null) { fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); } IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus }); fContext.statusChanged(status); } private boolean canBrowseFileName() { if (!isVariableEntry()) { return true; } // to browse with a variable JAR, the variable name must point to a directory if (fFileVariablePath != null) { return fFileVariablePath.toFile().isDirectory(); } return false; } private String getResolvedLabelString(String path, boolean osPath) { IPath resolvedPath= getResolvedPath(new Path(path)); if (resolvedPath != null) { if (osPath) { return resolvedPath.toOSString(); } else { return resolvedPath.toString(); } } return ""; //$NON-NLS-1$ } private IPath getResolvedPath(IPath path) { if (path != null) { String varName= path.segment(0); if (varName != null) { IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { return varPath.append(path.removeFirstSegments(1)); } } } return null; } private IStatus updateFileNameStatus() { StatusInfo status= new StatusInfo(); fFileVariablePath= null; String fileName= fFileNameField.getText(); if (fileName.length() == 0) { // no source attachment return status; } else { if (!Path.EMPTY.isValidPath(fileName)) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$ return status; } IPath filePath= new Path(fileName); IPath resolvedPath; if (isVariableEntry()) { if (filePath.getDevice() != null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.deviceinpath")); //$NON-NLS-1$ return status; } String varName= filePath.segment(0); if (varName == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$ return status; } fFileVariablePath= JavaCore.getClasspathVariable(varName); if (fFileVariablePath == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.varnotexists")); //$NON-NLS-1$ return status; } resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1)); if (resolvedPath.isEmpty()) { status.setWarning(NewWizardMessages.getString("SourceAttachmentBlock.filename.warning.varempty")); //$NON-NLS-1$ return status; } File file= resolvedPath.toFile(); if (!file.exists()) { String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", resolvedPath.toOSString()); //$NON-NLS-1$ status.setWarning(message); return status; } } else { File file= filePath.toFile(); IResource res= fWorkspaceRoot.findMember(filePath); if (res != null && res.getLocation() != null) { file= res.getLocation().toFile(); } if (!file.exists()) { String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", filePath.toString()); //$NON-NLS-1$ status.setError(message); return status; } } } return status; } private IPath chooseExtension() { IPath currPath= new Path(fFileNameField.getText()); if (currPath.isEmpty()) { currPath= fEntry.getPath(); } IPath resolvedPath= getResolvedPath(currPath); File initialSelection= resolvedPath != null ? resolvedPath.toFile() : null; String currVariable= currPath.segment(0); JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), false, true); dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.extvardialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.extvardialog.description")); //$NON-NLS-1$ dialog.setInput(fFileVariablePath.toFile()); dialog.setInitialSelection(initialSelection); if (dialog.open() == Window.OK) { File result= (File) dialog.getResult()[0]; IPath returnPath= new Path(result.getPath()).makeAbsolute(); return modifyPath(returnPath, currVariable); } return null; } /* * Opens a dialog to choose a jar from the file system. */ private IPath chooseExtJarFile() { IPath currPath= new Path(fFileNameField.getText()); if (currPath.isEmpty()) { currPath= fEntry.getPath(); } if (ArchiveFileFilter.isArchivePath(currPath)) { currPath= currPath.removeLastSegments(1); } FileDialog dialog= new FileDialog(getShell()); dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.extjardialog.text")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(currPath.toOSString()); String res= dialog.open(); if (res != null) { return new Path(res).makeAbsolute(); } return null; } private IPath chooseExtFolder() { IPath currPath= new Path(fFileNameField.getText()); if (currPath.isEmpty()) { currPath= fEntry.getPath(); } if (ArchiveFileFilter.isArchivePath(currPath)) { currPath= currPath.removeLastSegments(1); } DirectoryDialog dialog= new DirectoryDialog(getShell()); dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.extfolderdialog.text")); //$NON-NLS-1$ dialog.setFilterPath(currPath.toOSString()); String res= dialog.open(); if (res != null) { return new Path(res).makeAbsolute(); } return null; } /* * Opens a dialog to choose an internal jar. */ private IPath chooseInternalJarFile() { String initSelection= fFileNameField.getText(); Class[] acceptedClasses= new Class[] { IFolder.class, IFile.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); ViewerFilter filter= new ArchiveFileFilter(null, false); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSel= null; if (initSelection.length() > 0) { initSel= fWorkspaceRoot.findMember(new Path(initSelection)); } if (initSel == null) { initSel= fWorkspaceRoot.findMember(fEntry.getPath()); } FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp); dialog.setAllowMultiple(false); dialog.setValidator(validator); dialog.addFilter(filter); dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.message")); //$NON-NLS-1$ dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSel); if (dialog.open() == Window.OK) { IResource res= (IResource) dialog.getFirstResult(); return res.getFullPath(); } return null; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Takes a path and replaces the beginning with a variable name * (if the beginning matches with the variables value) */ private IPath modifyPath(IPath path, String varName) { if (varName == null || path == null) { return null; } if (path.isEmpty()) { return new Path(varName); } IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { if (varPath.isPrefixOf(path)) { path= path.removeFirstSegments(varPath.segmentCount()); } else { path= new Path(path.lastSegment()); } } else { path= new Path(path.lastSegment()); } return new Path(varName).append(path); } /** * Creates a runnable that sets the source attachment by modifying the project's classpath. * @deprecated use getRunnable() instead */ public IRunnableWithProgress getRunnable(final IJavaProject jproject, final Shell shell) { fProject= jproject; return getRunnable(shell); } /** * Creates a runnable that sets the source attachment by modifying the * project's classpath or updating a container. */ public IRunnableWithProgress getRunnable(final Shell shell) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { attachSource(shell, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } protected void attachSource(final Shell shell, IProgressMonitor monitor) throws CoreException { boolean isExported= fEntry.isExported(); IClasspathEntry newEntry; if (fEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { newEntry= JavaCore.newVariableEntry(fEntry.getPath(), getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported); } else { newEntry= JavaCore.newLibraryEntry(fEntry.getPath(), getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported); } if (fContainerPath != null) { updateContainerClasspath(fProject, fContainerPath, newEntry, monitor); } else { updateProjectClasspath(shell, fProject, newEntry, monitor); } } private void updateContainerClasspath(IJavaProject jproject, IPath containerPath, IClasspathEntry newEntry, IProgressMonitor monitor) throws CoreException { IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject); IClasspathEntry[] entries= container.getClasspathEntries(); IClasspathEntry[] newEntries= new IClasspathEntry[entries.length]; for (int i= 0; i < entries.length; i++) { IClasspathEntry curr= entries[i]; if (curr.getEntryKind() == newEntry.getEntryKind() && curr.getPath().equals(newEntry.getPath())) { newEntries[i]= newEntry; } else { newEntries[i]= curr; } } IClasspathContainer updatedContainer= new UpdatedClasspathContainer(container, newEntries); ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0)); initializer.requestClasspathContainerUpdate(containerPath, jproject, updatedContainer); monitor.worked(1); } private void updateProjectClasspath(Shell shell, IJavaProject jproject, IClasspathEntry newEntry, IProgressMonitor monitor) throws JavaModelException { IClasspathEntry[] oldClasspath= jproject.getRawClasspath(); int nEntries= oldClasspath.length; ArrayList newEntries= new ArrayList(nEntries + 1); int entryKind= newEntry.getEntryKind(); IPath jarPath= newEntry.getPath(); boolean found= false; for (int i= 0; i < nEntries; i++) { IClasspathEntry curr= oldClasspath[i]; if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) { // add modified entry newEntries.add(newEntry); found= true; } else { newEntries.add(curr); } } if (!found) { if (newEntry.getSourceAttachmentPath() == null || !putJarOnClasspathDialog(shell)) { return; } // add new newEntries.add(newEntry); } IClasspathEntry[] newClasspath= (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]); jproject.setRawClasspath(newClasspath, monitor); } private boolean putJarOnClasspathDialog(Shell shell) { final boolean[] result= new boolean[1]; shell.getDisplay().syncExec(new Runnable() { public void run() { String title= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.message"); //$NON-NLS-1$ result[0]= MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, message); } }); return result[0]; } }
44,411
Bug 44411 NPE in JavaSearchResultCollector [search]
Build 20030930 JavaSearchResultCollector.fView is null: Thread [ModalContext] (Suspended (exception NullPointerException)) JavaSearchResultCollector.accept(IResource, int, int, IJavaElement, int) line: 130 MatchLocator.report(IResource, int, int, IJavaElement, int) line: 923 MatchLocator.report(int, int, IJavaElement, int) line: 916 MatchLocator.reportAccurateReference(int, int, char[][], IJavaElement, int) line: 984 TypeReferenceLocator.matchReportReference(ArrayTypeReference, IJavaElement, int, MatchLocator) line: 162 TypeReferenceLocator.matchReportReference(AstNode, IJavaElement, int, MatchLocator) line: 176 MatchLocator.reportMatching(AbstractMethodDeclaration, IJavaElement, int, boolean, MatchingNodeSet) line: 1155 MatchLocator.reportMatching(TypeDeclaration, IJavaElement, int, MatchingNodeSet) line: 1330 MatchLocator.reportMatching(CompilationUnitDeclaration, boolean) line: 1216 MatchLocator.process(PossibleMatch, boolean) line: 857 MatchLocator.locateMatches(JavaProject, PossibleMatch[], int, int) line: 590 MatchLocator.locateMatches(JavaProject, PossibleMatchSet) line: 627 MatchLocator.locateMatches(String[], IWorkspace, ICompilationUnit[]) line: 714 SearchEngine.search(IWorkspace, ISearchPattern, IJavaSearchScope, IJavaSearchResultCollector) line: 568 SearchEngine.search(IWorkspace, IJavaElement, int, IJavaSearchScope, IJavaSearchResultCollector) line: 495 JavaSearchOperation.execute(IProgressMonitor) line: 96 WorkspaceModifyOperation$1.run(IProgressMonitor) line: 71 Workspace.run(IWorkspaceRunnable, ISchedulingRule, IProgressMonitor) line: 1555 Workspace.run(IWorkspaceRunnable, IProgressMonitor) line: 1572 JavaSearchOperation(WorkspaceModifyOperation).run(IProgressMonitor) line: 85 ModalContext$ModalContextThread.run() line: 101
resolved fixed
98623c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-08T12:47:49Z
2003-10-08T10:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultCollector.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import java.util.HashMap; 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.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.search.ui.IActionGroupFactory; import org.eclipse.search.ui.ISearchResultView; import org.eclipse.search.ui.SearchUI; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.search.IJavaSearchResultCollector; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog; public class JavaSearchResultCollector implements IJavaSearchResultCollector { private static final String MATCH= SearchMessages.getString("SearchResultCollector.match"); //$NON-NLS-1$ private static final String MATCHES= SearchMessages.getString("SearchResultCollector.matches"); //$NON-NLS-1$ private static final String DONE= SearchMessages.getString("SearchResultCollector.done"); //$NON-NLS-1$ private static final String SEARCHING= SearchMessages.getString("SearchResultCollector.searching"); //$NON-NLS-1$ private static final Boolean POTENTIAL_MATCH_VALUE= new Boolean(true); private static final String POTENTIAL_MATCH_DIALOG_ID= "Search.PotentialMatchDialog"; //$NON-NLS-1$ private IProgressMonitor fMonitor; private ISearchResultView fView; private JavaSearchOperation fOperation; private int fMatchCount= 0; private int fPotentialMatchCount= 0; private long fLastUpdateTime; private Integer[] fMessageFormatArgs= new Integer[1]; private class ActionGroupFactory implements IActionGroupFactory { public ActionGroup createActionGroup(ISearchResultView part) { return new SearchViewActionGroup(part); } } public JavaSearchResultCollector() { // This ensures that the image class is loaded correctly JavaPlugin.getDefault().getImageRegistry(); } /** * @see IJavaSearchResultCollector#aboutToStart(). */ public void aboutToStart() { fPotentialMatchCount= 0; fView= SearchUI.getSearchResultView(); fMatchCount= 0; fLastUpdateTime= 0; if (fView != null) { fView.searchStarted( new ActionGroupFactory(), fOperation.getSingularLabel(), fOperation.getPluralLabelPattern(), fOperation.getImageDescriptor(), JavaSearchPage.EXTENSION_POINT_ID, new JavaSearchResultLabelProvider(), new GotoMarkerAction(), new GroupByKeyComputer(), fOperation); } if (!getProgressMonitor().isCanceled()) getProgressMonitor().subTask(SEARCHING); } /** * @see IJavaSearchResultCollector#accept */ public void accept(IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy) throws CoreException { if (enclosingElement == null || accuracy == POTENTIAL_MATCH && SearchUI.arePotentialMatchesIgnored()) return; IMarker marker= resource.createMarker(SearchUI.SEARCH_MARKER); HashMap attributes; Object groupKey= enclosingElement; attributes= new HashMap(7); if (accuracy == POTENTIAL_MATCH) { fPotentialMatchCount++; attributes.put(SearchUI.POTENTIAL_MATCH, POTENTIAL_MATCH_VALUE); if (groupKey == null) groupKey= "?:null"; //$NON-NLS-1$ else groupKey= "?:" + enclosingElement.getHandleIdentifier(); //$NON-NLS-1$ } ICompilationUnit cu= SearchUtil.findCompilationUnit(enclosingElement); if (cu != null && cu.isWorkingCopy()) attributes.put(IJavaSearchUIConstants.ATT_IS_WORKING_COPY, new Boolean(true)); //$NON-NLS-1$ JavaCore.addJavaElementMarkerAttributes(attributes, enclosingElement); attributes.put(IJavaSearchUIConstants.ATT_JE_HANDLE_ID, enclosingElement.getHandleIdentifier()); attributes.put(IMarker.CHAR_START, new Integer(Math.max(start, 0))); attributes.put(IMarker.CHAR_END, new Integer(Math.max(end, 0))); if (enclosingElement instanceof IMember && ((IMember)enclosingElement).isBinary()) attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CF_EDITOR); else attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CU_EDITOR); marker.setAttributes(attributes); fView.addMatch(enclosingElement.getElementName(), groupKey, resource, marker); fMatchCount++; if (!getProgressMonitor().isCanceled() && System.currentTimeMillis() - fLastUpdateTime > 1000) { getProgressMonitor().subTask(getFormattedMatchesString(fMatchCount)); fLastUpdateTime= System.currentTimeMillis(); } } /** * @see IJavaSearchResultCollector#done(). */ public void done() { if (!getProgressMonitor().isCanceled()) { String matchesString= getFormattedMatchesString(fMatchCount); getProgressMonitor().setTaskName(MessageFormat.format(DONE, new String[]{matchesString})); } if (fView != null) { if (fPotentialMatchCount > 0) explainPotentialMatch(fPotentialMatchCount); fView.searchFinished(); } // Cut no longer unused references because the collector might be re-used fView= null; fMonitor= null; } private void explainPotentialMatch(final int potentialMatchCount) { // Make sure we are doing it in the right thread. final Shell shell= fView.getSite().getShell(); final String title; if (potentialMatchCount == 1) title= new String(SearchMessages.getString("Search.potentialMatchDialog.title.foundPotentialMatch")); //$NON-NLS-1$ else title= new String(SearchMessages.getFormattedString("Search.potentialMatchDialog.title.foundPotentialMatches", "" + potentialMatchCount)); //$NON-NLS-1$ //$NON-NLS-2$ shell.getDisplay().syncExec(new Runnable() { public void run() { OptionalMessageDialog.open( POTENTIAL_MATCH_DIALOG_ID, //$NON-NLS-1$, shell, title, null, SearchMessages.getString("Search.potentialMatchDialog.message"), //$NON-NLS-1$, MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); } }); } /* * @see IJavaSearchResultCollector#getProgressMonitor(). */ public IProgressMonitor getProgressMonitor() { return fMonitor; } void setProgressMonitor(IProgressMonitor pm) { fMonitor= pm; } void setOperation(JavaSearchOperation operation) { fOperation= operation; } private String getFormattedMatchesString(int count) { if (fMatchCount == 1) return MATCH; fMessageFormatArgs[0]= new Integer(count); return MessageFormat.format(MATCHES, fMessageFormatArgs); } }
44,401
Bug 44401 rename refactoring should be disabled for anonymous types [refactoring]
null
resolved fixed
fac5b81
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-08T15:00:34Z
2003-10-08T10:46:40Z
org.eclipse.jdt.ui/core
44,401
Bug 44401 rename refactoring should be disabled for anonymous types [refactoring]
null
resolved fixed
fac5b81
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-08T15:00:34Z
2003-10-08T10:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/participants/xml/TypePropertyTester.java
44,407
Bug 44407 Change method signature does nothing for local types [refactoring]
Test pass M4. Title says it all.
resolved fixed
2d5e0f1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-08T17:10:30Z
2003-10-08T10:46:40Z
org.eclipse.jdt.ui/core
44,407
Bug 44407 Change method signature does nothing for local types [refactoring]
Test pass M4. Title says it all.
resolved fixed
2d5e0f1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-08T17:10:30Z
2003-10-08T10:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
44,514
Bug 44514 NPE from JavaModel
Build: I-200310081556 I opened a call hierarchy on the method ClasspathUtilCore.addMissingProjectAsDependency(...) Once I double-clicked on the method container.put(..) in the call hierarchy, I got the following NPE: Error Oct 08, 2003 22:46:36.473 Problems occurred when invoking code from plug- in: "org.eclipse.jface". java.lang.NullPointerException at org.eclipse.jdt.internal.corext.util.JavaModelUtil.toOriginal (JavaModelUtil.java:601) at org.eclipse.jdt.internal.corext.callhierarchy.CallLocation.getICompilationUnit (CallLocation.java:101) at org.eclipse.jdt.internal.corext.callhierarchy.CallLocation.getCallText (CallLocation.java:108) at org.eclipse.jdt.internal.ui.callhierarchy.LocationLabelProvider.removeWhitespac eOutsideStringLiterals(LocationLabelProvider.java:50) at org.eclipse.jdt.internal.ui.callhierarchy.LocationLabelProvider.getColumnText (LocationLabelProvider.java:104) at org.eclipse.jface.viewers.TableViewer.doUpdateItem (TableViewer.java:196) at org.eclipse.jface.viewers.StructuredViewer$UpdateItemSafeRunnable.run (StructuredViewer.java:119) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1018) at org.eclipse.core.runtime.Platform.run(Platform.java:461) at org.eclipse.jface.viewers.StructuredViewer.updateItem (StructuredViewer.java:1263) at org.eclipse.jface.viewers.TableViewer.internalRefresh (TableViewer.java:488) at org.eclipse.jface.viewers.TableViewer.internalRefresh (TableViewer.java:431) at org.eclipse.jface.viewers.StructuredViewer$7.run (StructuredViewer.java:856) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:796) at org.eclipse.jface.viewers.StructuredViewer.refresh (StructuredViewer.java:854) at org.eclipse.jface.viewers.StructuredViewer.refresh (StructuredViewer.java:816) at org.eclipse.jface.viewers.TableViewer.inputChanged (TableViewer.java:398) at org.eclipse.jface.viewers.ContentViewer.setInput (ContentViewer.java:238) at org.eclipse.jface.viewers.StructuredViewer.setInput (StructuredViewer.java:983) at org.eclipse.jdt.internal.ui.callhierarchy.CallHierarchyViewPart.updateLocations View(CallHierarchyViewPart.java:884) at org.eclipse.jdt.internal.ui.callhierarchy.CallHierarchyViewPart.methodSelection Changed(CallHierarchyViewPart.java:621) at org.eclipse.jdt.internal.ui.callhierarchy.CallHierarchyViewPart.selectionChange d(CallHierarchyViewPart.java:606) at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:159) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1018) at org.eclipse.core.runtime.Platform.run(Platform.java:461) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:157) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1282) at org.eclipse.jface.viewers.StructuredViewer.handleSelect (StructuredViewer.java:652) at org.eclipse.jface.viewers.StructuredViewer$4.widgetSelected (StructuredViewer.java:676) at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent (OpenStrategy.java:178) at org.eclipse.jface.util.OpenStrategy.access$3(OpenStrategy.java:173) at org.eclipse.jface.util.OpenStrategy$1.handleEvent (OpenStrategy.java:309) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2334) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2317) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
resolved fixed
0954d67
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-09T10:49:42Z
2003-10-09T03:26:40Z
org.eclipse.jdt.ui/core
44,514
Bug 44514 NPE from JavaModel
Build: I-200310081556 I opened a call hierarchy on the method ClasspathUtilCore.addMissingProjectAsDependency(...) Once I double-clicked on the method container.put(..) in the call hierarchy, I got the following NPE: Error Oct 08, 2003 22:46:36.473 Problems occurred when invoking code from plug- in: "org.eclipse.jface". java.lang.NullPointerException at org.eclipse.jdt.internal.corext.util.JavaModelUtil.toOriginal (JavaModelUtil.java:601) at org.eclipse.jdt.internal.corext.callhierarchy.CallLocation.getICompilationUnit (CallLocation.java:101) at org.eclipse.jdt.internal.corext.callhierarchy.CallLocation.getCallText (CallLocation.java:108) at org.eclipse.jdt.internal.ui.callhierarchy.LocationLabelProvider.removeWhitespac eOutsideStringLiterals(LocationLabelProvider.java:50) at org.eclipse.jdt.internal.ui.callhierarchy.LocationLabelProvider.getColumnText (LocationLabelProvider.java:104) at org.eclipse.jface.viewers.TableViewer.doUpdateItem (TableViewer.java:196) at org.eclipse.jface.viewers.StructuredViewer$UpdateItemSafeRunnable.run (StructuredViewer.java:119) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1018) at org.eclipse.core.runtime.Platform.run(Platform.java:461) at org.eclipse.jface.viewers.StructuredViewer.updateItem (StructuredViewer.java:1263) at org.eclipse.jface.viewers.TableViewer.internalRefresh (TableViewer.java:488) at org.eclipse.jface.viewers.TableViewer.internalRefresh (TableViewer.java:431) at org.eclipse.jface.viewers.StructuredViewer$7.run (StructuredViewer.java:856) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:796) at org.eclipse.jface.viewers.StructuredViewer.refresh (StructuredViewer.java:854) at org.eclipse.jface.viewers.StructuredViewer.refresh (StructuredViewer.java:816) at org.eclipse.jface.viewers.TableViewer.inputChanged (TableViewer.java:398) at org.eclipse.jface.viewers.ContentViewer.setInput (ContentViewer.java:238) at org.eclipse.jface.viewers.StructuredViewer.setInput (StructuredViewer.java:983) at org.eclipse.jdt.internal.ui.callhierarchy.CallHierarchyViewPart.updateLocations View(CallHierarchyViewPart.java:884) at org.eclipse.jdt.internal.ui.callhierarchy.CallHierarchyViewPart.methodSelection Changed(CallHierarchyViewPart.java:621) at org.eclipse.jdt.internal.ui.callhierarchy.CallHierarchyViewPart.selectionChange d(CallHierarchyViewPart.java:606) at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:159) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1018) at org.eclipse.core.runtime.Platform.run(Platform.java:461) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:157) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1282) at org.eclipse.jface.viewers.StructuredViewer.handleSelect (StructuredViewer.java:652) at org.eclipse.jface.viewers.StructuredViewer$4.widgetSelected (StructuredViewer.java:676) at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent (OpenStrategy.java:178) at org.eclipse.jface.util.OpenStrategy.access$3(OpenStrategy.java:173) at org.eclipse.jface.util.OpenStrategy$1.handleEvent (OpenStrategy.java:309) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2334) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2317) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
resolved fixed
0954d67
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-09T10:49:42Z
2003-10-09T03:26:40Z
extension/org/eclipse/jdt/internal/corext/callhierarchy/CallLocation.java
44,624
Bug 44624 tomcat launcher not usable
M4 candidate If I create a tomcat launch config, I am told that catalina_home is not defined. However, there is no way to define the variable. (I did set catalina_home in Run/Debug->String Substitution, but I still get "variable not defined" in the launch config dialog.
verified fixed
28e1f11
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-10T13:38:56Z
2003-10-09T22:53:20Z
org.eclipse.jdt.ui.examples.javafamily/src/org/eclipse/jsp/launching/TomcatLaunchDelegate.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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.jsp.launching; import java.io.File; import java.text.MessageFormat; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.internal.core.stringsubstitution.IValueVariable; import org.eclipse.jdt.debug.core.IJavaDebugTarget; import org.eclipse.jdt.internal.launching.JavaLocalApplicationLaunchConfigurationDelegate; import org.eclipse.jsp.JspUIPlugin; /** * Launch delegate for a local Tomcat server */ public class TomcatLaunchDelegate extends JavaLocalApplicationLaunchConfigurationDelegate { /** * Identifier for Tomcat launch configurations. */ public static final String ID_TOMCAT_LAUNCH_CONFIGURATION_TYPE = "org.eclipse.jsp.TomcatConfigurationType"; //$NON-NLS-1$ /** * Identifier for Tomcat classpath provider. */ public static final String ID_TOMCAT_CLASSPATH_PROVIDER = "org.eclipse.jsp.tomcatClasspathProvider"; //$NON-NLS-1$ /** * Launch configuration attribute - value is path to local installation of Tomcat. * The path may be encoded in a launch variable. */ public static final String ATTR_CATALINA_HOME = "org.eclipse.jsp.CATALINA_HOME"; //$NON-NLS-1$ /** * Launch configuration attribute - value is a workspace relative path to the root * folder of a web application. */ public static final String ATTR_WEB_APP_ROOT= "org.eclipse.jsp.WEB_APP_ROOT"; //$NON-NLS-1$ /* (non-Javadoc) * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor) */ public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { super.launch(configuration, mode, launch, monitor); // set default stratum IJavaDebugTarget target = (IJavaDebugTarget)launch.getDebugTarget(); if (target != null) { // only available in debug mode target.setDefaultStratum("JSP"); //$NON-NLS-1$ \ } } /** * Constructs a new launch delegate */ public TomcatLaunchDelegate() { super(); } /** * Returns the value of the <code>${catalina_home}</code> launch variable. * * @return the value of the <code>${catalina_home}</code> launch variable * @exception CoreException if the variable or value is undefined */ public static String getCatalinaHome() throws CoreException { IValueVariable variable = DebugPlugin.getDefault().getStringVariableManager().getValueVariable("${catalina_home}"); //$NON-NLS-1$ IStatus err = null; if (variable == null) { err = new Status(IStatus.ERROR, JspUIPlugin.getDefault().getDescriptor().getUniqueIdentifier(), 0, LaunchingMessages.getString("TomcatLaunchDelegate.9"), null); //$NON-NLS-1$ } else { String home = variable.getValue(); if (home != null && home.length() > 0) { File file = new File(home); if (file.exists() && file.isDirectory()) { return home; } else { err = new Status(IStatus.ERROR, JspUIPlugin.getDefault().getDescriptor().getUniqueIdentifier(), 0, MessageFormat.format(LaunchingMessages.getString("TomcatLaunchDelegate.7"), new String[]{home}), null); //$NON-NLS-1$ } } else { err = new Status(IStatus.ERROR, JspUIPlugin.getDefault().getDescriptor().getUniqueIdentifier(), 0, LaunchingMessages.getString("TomcatLaunchDelegate.8"), null); //$NON-NLS-1$ } } throw new CoreException(err); } }
30,468
Bug 30468 enhanced smart pasting
consider the following file: public class Test { public void method() { String x = "hello"; } public class C { } } ------------------- if you select the method starting the 'p' in "public void method()" and paste it just below with smart pasting enabled you get the following: public class Test { public void method() { String x = "hello"; } public void method() { String x = "hello"; } public class C { } } If you then paste it as part of class C you get the following: public class Test { public void method() { String x = "hello"; } public void method() { String x = "hello"; } public class C { public void method() { String x = "hello"; } } } It would be nice if the brackets line up with the method. This can probably be achieved if you treat the first line of the pasted text as different to the other lines because you cannot guarentee that text selection will always start from the beginning of the line with the correct ammount of tabs/spaces in the first line of a selection.
resolved fixed
928b0eb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-13T14:26:24Z
2003-01-29T08:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Uses the {@link org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner} to get the indentation * level for a certain position in a document. * * <p>An instance holds some internal position in the document and is therefore not threadsafe.</p> * * @since 3.0 */ public class JavaIndenter { /** The document being scanned. */ private IDocument fDocument; /** The indentation accumulated by <code>findPreviousIndenationUnit</code>. */ private int fIndent; /** The absolute (character-counted) indentation offset for special cases (method defs, array initializers) */ private int fAlign; /** Whether to add one space to the absolute indentation. */ private boolean fAlignPlusOne; /** The stateful scanpositionf or the indentation methods. */ private int fPosition; /** The previous position. */ private int fPreviousPos; /** The most recent token. */ private int fToken; /** * The scanner we will use to scan the document. It has to be installed on the same document * as the one we get. */ private JavaHeuristicScanner fScanner; /** * Creates a new instance. * * @param document the document to scan */ public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) { Assert.isNotNull(document); Assert.isNotNull(scanner); fDocument= document; fScanner= scanner; } /** * Computes the indentation at the reference point of <code>position</code>. * * @param position the position in the document, either at the beginning of a line or in the * whitespace at the beginning of a line * @return a String which reflects the indentation at the line in which the reference position * to <code>position</code> resides, or <code>null</code> if it cannot be determined. */ public String getReferenceIndentation(int position) { try { // account for unindenation characters already typed in, but after position // also account for a dangling else boolean danglingElse= false; boolean matchBrace= false; if (position < fDocument.getLength()) { IRegion line= fDocument.getLineInformationOfOffset(position); int next= fScanner.nextToken(position, line.getOffset() + line.getLength()); switch (next) { case Symbols.TokenEOF: case Symbols.TokenELSE: danglingElse= true; break; case Symbols.TokenRBRACE: // closing braces get unindented matchBrace= true; } } else { danglingElse= true; } // find the base position int unit= findReferencePosition(position, danglingElse, matchBrace); // if we were unable to find anything, return null if (unit == JavaHeuristicScanner.NOT_FOUND) return null; //$NON-NLS-1$ // get base indent at the reference location IRegion line= fDocument.getLineInformationOfOffset(unit); int offset= line.getOffset(); int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(offset, offset + line.getLength()); StringBuffer indent= new StringBuffer(fDocument.get(offset, nonWS - offset)); return indent.toString(); } catch (BadLocationException e) { } return null; } /** * Computes the indentation at <code>position</code>. * * @param position the position in the document, either at the beginning of a line or in the * whitespace at the beginning of a line * @return a String which reflects the correct indentation for the line in which position * resides, or <code>null</code> if it cannot be determined.. */ public String computeIndentation(int position) { try { // account for unindenation characters already typed in, but after position // also account for a dangling else boolean danglingElse= false; boolean unindent= false; boolean matchBrace= false; if (position < fDocument.getLength()) { IRegion line= fDocument.getLineInformationOfOffset(position); int next= fScanner.nextToken(position, line.getOffset() + line.getLength()); int prevPos= Math.max(position - 1, 0); switch (next) { case Symbols.TokenEOF: case Symbols.TokenELSE: danglingElse= true; break; case Symbols.TokenCASE: case Symbols.TokenDEFAULT: // only if not right after the brace! if (prefAlignCaseWithSwitch() || fScanner.previousToken(prevPos, JavaHeuristicScanner.UNBOUND) != Symbols.TokenLBRACE) unindent= true; break; case Symbols.TokenLBRACE: // for opening-brace-on-new-line style if (fScanner.isBracelessBlockStart(prevPos, JavaHeuristicScanner.UNBOUND)) unindent= true; break; case Symbols.TokenRBRACE: // closing braces get unindented matchBrace= true; break; case Symbols.TokenWHILE: break; } } else { danglingElse= true; // assume an else could come - align with 'if' } // find the base position int unit= findReferencePosition(position, danglingElse, matchBrace); // handle special alignment if (fAlign != JavaHeuristicScanner.NOT_FOUND) { // a special case has been detected. IRegion line= fDocument.getLineInformationOfOffset(fAlign); int offset= line.getOffset(); return createIndent(offset, fAlign); } // if we were unable to find anything, return null if (unit == JavaHeuristicScanner.NOT_FOUND) return null; //$NON-NLS-1$ // get base indent at the reference location IRegion line= fDocument.getLineInformationOfOffset(unit); int offset= line.getOffset(); int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(offset, offset + line.getLength()); StringBuffer indent= new StringBuffer(fDocument.get(offset, nonWS - offset)); // add additional indent indent.append(createIndent(fIndent)); if (unindent) unindent(indent); return indent.toString(); } catch (BadLocationException e) { } return null; //$NON-NLS-1$ } /** * Reduces indentation in <code>indent</code> by one. * * @param indent the indentation to be modified */ private void unindent(StringBuffer indent) { String oneIndent= createIndent(1); int i= indent.lastIndexOf(oneIndent); //$NON-NLS-1$ if (i != -1) { indent.deleteCharAt(i); } } /** * Creates an indentation string of the length indent - start + 1, consisting of the content * in <code>fDocument</code> in the range [start, indent), with every character replaced by * a space except for tabs, which are kept as such. * * @return the indentation corresponding to the document content specified by <code>start</code> * and <code>indent</code> */ private String createIndent(int start, int indent) { int tabLen; if (JavaPlugin.getDefault() != null) tabLen= CodeFormatterUtil.getTabWidth(); else tabLen= 4; StringBuffer ret= new StringBuffer(); try { int spaces= 0; while (start < indent) { char ch= fDocument.getChar(start); if (ch == '\t') { ret.append('\t'); spaces= 0; } else { spaces++; if (spaces == tabLen) { ret.append('\t'); spaces= 0; } } start++; } if (fAlignPlusOne) spaces++; if (spaces == tabLen) ret.append('\t'); else while (spaces-- > 0) ret.append(' '); } catch (BadLocationException e) { } return ret.toString(); } /** * Creates a string that represents the given number of indents (can be spaces or tabs..) * @param indent the requested indentation level. * * @return the indentation specified by <code>indent</code> */ private String createIndent(int indent) { // get a sensible default when running without the infrastructure for testing if (JavaPlugin.getDefault() == null) { StringBuffer ret= new StringBuffer(); while (indent-- > 0) ret.append('\t'); return ret.toString(); } return CodeFormatterUtil.createIndentString(indent); } /** * Returns the reference position regarding to indentation for <code>position</code>, or * <code>NOT_FOUND</code>. <code>fIndent</code> will contain the relative indentation (in * indentation units, not characters) after the call. If there is a special alignment (e.g. for * a method declaration where parameters should be aligned), <code>fAlign</code> will contain the absolute * position of the alignment reference in <code>fDocument</code>, otherwise <code>fAlign</code> * is set to <code>JavaHeuristicScanner.NOT_FOUND</code>. * * @param position the position for which the reference is computed * @return the reference statement relative to which <code>position</code> should be indented. */ public int findReferencePosition(int position) { return findReferencePosition(position, false, false); } /** * Returns the reference position regarding to indentation for <code>position</code>, or * <code>NOT_FOUND</code>. <code>fIndent</code> will contain the relative indentation (in * indentation units, not characters) after the call. If there is a special alignment (e.g. for * a method declaration where parameters should be aligned), <code>fAlign</code> will contain the absolute * position of the alignment reference in <code>fDocument</code>, otherwise <code>fAlign</code> * is set to <code>JavaHeuristicScanner.NOT_FOUND</code>. * * @param position the position for which the reference is computed * @param danglingElse whether a dangling else should be assumed at <code>position</code> * @param matchBrace whether the position of the matching brace should be returned instead of doing code analysis * @return the reference statement relative to which <code>position</code> should be indented. */ private int findReferencePosition(int position, boolean danglingElse, boolean matchBrace) { fIndent= 0; // the indentation modification fAlign= JavaHeuristicScanner.NOT_FOUND; fPosition= position; boolean indentBlockLess= true; // whether to indent after an if / while / for without block (set false by semicolons and braces) boolean takeNextExit= true; // whether the next possible exit should be taken (instead of looking for the base; see blockless stuff) boolean found= false; // whether we have found anything at all. If we have, we'll trace back to it once we have a hoist point boolean hasBrace= false; if (matchBrace) { if (!skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE)) fPosition= position; else { indentBlockLess= false; hasBrace= true; } } nextToken(); while (true) { switch (fToken) { // skip all scopes introduced by parenthesis' or brackets: case Symbols.TokenRBRACKET: skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET); nextToken(); break; case Symbols.TokenRPAREN: skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN); // handle special indentations: non-block conditionals nextToken(); int pos= fPosition; switch (fToken) { case Symbols.TokenWHILE: if (hasMatchingDo()) { nextToken(); break; } else { nextToken(pos); } case Symbols.TokenIF: if (danglingElse && fToken == Symbols.TokenIF) takeNextExit= true; case Symbols.TokenFOR: if (indentBlockLess) fIndent++; if (takeNextExit) return pos; } break; case Symbols.TokenDO: // do blockless special if (indentBlockLess) { fIndent++; return fPosition; } else if (hasBrace) { return fPosition; } else { fIndent= 0; // after a do, there is a mandatory while on the same level return fPosition; } case Symbols.TokenELSE: // else blockless special if (indentBlockLess) fIndent++; if (takeNextExit) return fPosition; // else if (!searchIfForElse()) return JavaHeuristicScanner.NOT_FOUND; nextToken(); break; case Symbols.TokenCOLON: // switch statements and labels if (searchCaseGotoDefault()) { if (!hasBrace) fIndent++; return fPosition; } break; case Symbols.TokenQUESTIONMARK: // ternary expressions if (takeNextExit && prefTenaryDeepAlign()) fAlign= fPosition; nextToken(); break; // When we find a semi or lbrace, we have found a hoist point // Take the first start to the right from it. If there is only whitespace // up to position, search one step more. case Symbols.TokenLBRACE: int searchPos= fPreviousPos; // special array handling nextToken(); if (fToken == Symbols.TokenEQUAL || skipBrackets()) { int first= fScanner.findNonWhitespaceForwardInAnyPartition(searchPos, position); // ... with a first element already defined - take its offset if (prefArrayDeepIndent() && first != JavaHeuristicScanner.NOT_FOUND) { fAlign= first; } else fIndent += prefArrayIndent(); } hasBrace= true; if (found) return fScanner.findNonWhitespaceForward(searchPos, position); // search start of code forward or continue takeNextExit= true; indentBlockLess= false; // indent when searching over an LBRACE fIndent++; break; case Symbols.TokenSEMICOLON: // search start of code forward or continue if (found) return fScanner.findNonWhitespaceForward(fPreviousPos, position); takeNextExit= false; // search to the bottom of blockless statements indentBlockLess= false; // don't indent at the next blockless introducer nextToken(); break; case Symbols.TokenEOF: if (found) return fScanner.findNonWhitespaceForward(0, position); return JavaHeuristicScanner.NOT_FOUND; // RBRACE is either the end of a statement as SEMICOLON, // or - if no statement start can be found - must be skipped as RPAREN and RBRACKET case Symbols.TokenRBRACE: if (found && fScanner.nextToken(fPreviousPos, position) != Symbols.TokenSEMICOLON) // don't take it for array initializers return fScanner.findNonWhitespaceForward(fPreviousPos, position); skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE); takeNextExit= false; // search to the bottom of blockless statements indentBlockLess= false; // don't indent at the next blockless introducer nextToken(); break; // use double indentation inside conditions and calls // handle method definitions separately case Symbols.TokenLPAREN: // TODO differentiate between conditional continuation and calls if (!hasBrace) fIndent += prefCallContinuationIndent(); searchPos= fPreviousPos; if (prefMethodDeclDeepIndent() && looksLikeMethodDecl() && found) { fAlign= fScanner.findNonWhitespaceForward(searchPos, position); } break; // array dimensions case Symbols.TokenLBRACKET: if (prefArrayDimensionsDeepIndent() && found) fAlign= fScanner.findNonWhitespaceForward(fPreviousPos, position); fIndent+= prefArrayDimensionIndent(); nextToken(); break; case Symbols.TokenCOMMA: if (found) fScanner.findNonWhitespaceForward(fPreviousPos, position); nextToken(); break; default: nextToken(); } found= true; } } /** * Searches for a case, goto, or default after a scanned colon. * * @return <code>true</code> if one of the above keywords can be scanned, possibly separated * by an identifier or constant. */ private boolean searchCaseGotoDefault() { // after a colon while (true) { nextToken(); switch (fToken) { // number or char literals won't bother us, no scopes allowed case Symbols.TokenOTHER: case Symbols.TokenIDENT: break; case Symbols.TokenEOF: return false; case Symbols.TokenCASE: case Symbols.TokenDEFAULT: case Symbols.TokenGOTO: return true; default: return false; } } } /** * while(condition); is ambiguous when parsed backwardly, as it is a valid statement by its own, * so we have to check whether there is a matching do. A <code>do</code> can either be separated * from the while by a block, or by a single statement, which limits our search distance. * * @return <code>true</code> if the <code>while</code> currently in <code>fToken</code> has a matching <code>do</code>. */ private boolean hasMatchingDo() { Assert.isTrue(fToken == Symbols.TokenWHILE); return skipStatementOrBlock() && fToken == Symbols.TokenDO; } /** * Skips a statement or block, the token being the next token after it. * * @return <code>true</code> if a statement or block could be parsed, <code>false</code> otherwise. */ private boolean skipStatementOrBlock() { nextToken(); switch (fToken) { case Symbols.TokenRBRACE: // do { BLOCK } while if (skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE)) { nextToken(); return true; } break; case Symbols.TokenSEMICOLON: // do statement; while nextToken(); while (true) { switch (fToken) { case Symbols.TokenRBRACE: // array definition skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE); nextToken(); if (skipBrackets()) break; else return false; case Symbols.TokenRBRACKET: // array index skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET); break; case Symbols.TokenRPAREN: // call, if , for, ..., step over skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN); break; case Symbols.TokenSEMICOLON: return true; case Symbols.TokenLBRACE: return true; case Symbols.TokenLPAREN: return false; case Symbols.TokenLBRACKET: return false; case Symbols.TokenDO: return true; case Symbols.TokenIF: return true; case Symbols.TokenFOR: return true; case Symbols.TokenWHILE: return true; case Symbols.TokenEOF: return false; } nextToken(); } } return false; } /** * Skips brackets if the current token is a RBRACKET. There can be nothing in between, this is * only to be used for <code>[]</code> elements. * * @return <code>true</code> if a <code>[]</code> could be scanned, the current token is left at * the LBRACKET. */ private boolean skipBrackets() { if (fToken == Symbols.TokenRBRACKET) { nextToken(); if (fToken == Symbols.TokenLBRACKET) { return true; } } return false; } /** * Searches for the <code>if</code> matching a just scanned else. * * @return <code>true</code> if the matching if can be found, <code>false</code> otherwise */ private boolean searchIfForElse() { int depth= 1; while (true) { nextToken(); switch (fToken) { case Symbols.TokenRBRACE: skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE); break; case Symbols.TokenIF: depth--; if (depth == 0) return true; break; case Symbols.TokenELSE: depth++; break; case Symbols.TokenEOF: return false; } } } /** * Reads the next token in backward direction from the heuristic scanner and sets the fields * <code>fToken, fPreviousPosition</code> and <code>fPosition</code> accordingly. */ private void nextToken() { nextToken(fPosition); } /** * Reads the next token in backward direction of <code>start</code> from the heuristic scanner and sets the fields * <code>fToken, fPreviousPosition</code> and <code>fPosition</code> accordingly. */ private void nextToken(int start) { fToken= fScanner.previousToken(start - 1, JavaHeuristicScanner.UNBOUND); fPreviousPos= start; fPosition= fScanner.getPosition() + 1; } /** * Returns <code>true</code> if the current tokens look like a method declaration header * (i.e. only the return type and method name). * * @return <code>true</code> if the current position looks like a method header. */ private boolean looksLikeMethodDecl() { nextToken(); if (fToken == Symbols.TokenIDENT) { // method name do nextToken(); while (skipBrackets()); // optional brackets for array valued return types return fToken == Symbols.TokenIDENT; // type name } return false; } /** * Scans tokens for the matching parenthesis. * * @return <code>true</code> if a matching token was found, <code>false</code> otherwise */ private boolean skipScope(int openToken, int closeToken) { int depth= 1; while (true) { nextToken(); if (fToken == closeToken) { depth++; } else if (fToken == openToken) { depth--; if (depth == 0) return true; } else if (fToken == Symbols.TokenEOF) { return false; } } } private boolean prefAlignCaseWithSwitch() { // TODO preference lookup return false; } private int prefArrayDimensionIndent() { // TODO preference lookup return 2; } private boolean prefArrayDimensionsDeepIndent() { // TODO preference lookup return true; } private boolean prefMethodDeclDeepIndent() { // TODO preference lookup return true; } private int prefCallContinuationIndent() { // TODO preference lookup return 2; } private int prefArrayIndent() { // TODO preference lookup return 2; } private boolean prefArrayDeepIndent() { // TODO preference lookup return false; } private boolean prefTenaryDeepAlign() { // TODO preference lookup return true; } }
30,468
Bug 30468 enhanced smart pasting
consider the following file: public class Test { public void method() { String x = "hello"; } public class C { } } ------------------- if you select the method starting the 'p' in "public void method()" and paste it just below with smart pasting enabled you get the following: public class Test { public void method() { String x = "hello"; } public void method() { String x = "hello"; } public class C { } } If you then paste it as part of class C you get the following: public class Test { public void method() { String x = "hello"; } public void method() { String x = "hello"; } public class C { public void method() { String x = "hello"; } } } It would be nice if the brackets line up with the method. This can probably be achieved if you treat the first line of the pasted text as different to the other lines because you cannot guarentee that text selection will always start from the beginning of the line with the correct ammount of tabs/spaces in the first line of a selection.
resolved fixed
928b0eb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-13T14:26:24Z
2003-01-29T08:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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 * Nikolay Metchev - Fixed bug 29909 *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import java.util.Iterator; import java.util.NoSuchElementException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.texteditor.ITextEditorExtension3; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.DoStatement; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.WhileStatement; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.dom.NodeFinder; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner; import org.eclipse.jdt.internal.ui.text.JavaIndenter; import org.eclipse.jdt.internal.ui.text.Symbols; /** * Auto indent strategy sensitive to brackets. */ public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy { /** * Internal line interator working on <code>IDocument</code>. */ 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 class CompilationUnitInfo { public char[] buffer; public int delta; public CompilationUnitInfo(char[] buffer, int delta) { this.buffer= buffer; this.delta= delta; } } private final static String COMMENT= "//"; //$NON-NLS-1$ private int fTabWidth; private boolean fUseSpaces; private boolean fCloseBrace; private boolean fIsSmartMode; private String fPartitioning; /** * Creates a new Java auto indent strategy for the given document partitioning. * * @param partitioning the document partitioning */ public JavaAutoIndentStrategy(String partitioning) { fPartitioning= partitioning; } /** * Evaluates the given line for the opening bracket that matches the closing bracket on the given line. */ private int findMatchingOpenBracket(IDocument d, int lineNumber, int endOffset, int closingBracketIncrease) throws BadLocationException { int startOffset= d.getLineOffset(lineNumber); int bracketCount= getBracketCount(d, startOffset, endOffset, 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 (bracketCount < 0) { --lineNumber; if (lineNumber < 0) return -1; startOffset= d.getLineOffset(lineNumber); endOffset= startOffset + d.getLineLength(lineNumber) - 1; bracketCount += getBracketCount(d, startOffset, endOffset, false); } return lineNumber; } private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException { int bracketCount= 0; while (startOffset < endOffset) { char curr= d.getChar(startOffset); startOffset++; switch (curr) { case '/' : if (startOffset < endOffset) { char next= d.getChar(startOffset); if (next == '*') { // a comment starts, advance to the comment end startOffset= getCommentEnd(d, startOffset + 1, endOffset); } else if (next == '/') { // '//'-comment: nothing to do anymore on this line startOffset= endOffset; } } break; case '*' : if (startOffset < endOffset) { char next= d.getChar(startOffset); if (next == '/') { // we have been in a comment: forget what we read before bracketCount= 0; startOffset++; } } break; case '{' : bracketCount++; ignoreCloseBrackets= false; break; case '}' : if (!ignoreCloseBrackets) { bracketCount--; } break; case '"' : case '\'' : startOffset= getStringEnd(d, startOffset, endOffset, curr); break; default : } } return bracketCount; } // ----------- bracket counting ------------------------------------------------------ private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException { while (offset < endOffset) { char curr= d.getChar(offset); offset++; if (curr == '*') { if (offset < endOffset && d.getChar(offset) == '/') { return offset + 1; } } } return endOffset; } private 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 offset, int endOffset, char ch) throws BadLocationException { while (offset < endOffset) { char curr= d.getChar(offset); offset++; if (curr == '\\') { // ignore escaped characters offset++; } else if (curr == ch) { return offset; } } return endOffset; } private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); int start= d.getLineOffset(line); int whiteend= findEndOfWhiteSpace(d, start, c.offset); // shift only when line does not contain any text up to the closing bracket if (whiteend == c.offset) { // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1 && indLine != line) { // take the indent of the found line StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine)); // add the rest of the current line including the just added close bracket replaceText.append(d.get(whiteend, c.offset - whiteend)); replaceText.append(c.text); // modify document command c.length += c.offset - start; c.offset= start; c.text= replaceText.toString(); } } } catch (BadLocationException e) { JavaPlugin.log(e); } } private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) { if (c.offset < 1 || d.getLength() == 0) return; JavaHeuristicScanner scanner= new JavaHeuristicScanner(d); int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); try { // current line int line= d.getLineOfOffset(p); int lineOffset= d.getLineOffset(line); // line of last javacode int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND); if (pos == -1) return; int lastLine= d.getLineOfOffset(pos); // only shift if the last java line is further up and is a braceless block candidate if (lastLine < line) { if (scanner.isBracelessBlockStart(pos + 1, JavaHeuristicScanner.UNBOUND)) { // if the last line was a braceless block candidate, we have indented // after the new line. This has to be undone as we *are* starting a block // on the new line StringBuffer replace= new StringBuffer(getIndentOfLine(d, lastLine)); c.length += replace.length(); replace.append(c.text); c.offset= lineOffset; c.text= replace.toString(); } } } catch (BadLocationException e) { JavaPlugin.log(e); } } private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) { JavaHeuristicScanner scanner= new JavaHeuristicScanner(d); JavaIndenter indenter= new JavaIndenter(d, scanner); String indent= indenter.computeIndentation(c.offset); if (indent == null) indent= ""; //$NON-NLS-1$ 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 + indent); IRegion reg= d.getLineInformation(line); int lineEnd= reg.getOffset() + reg.getLength(); int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd); c.length= Math.max(contentStart - c.offset, 0); int start= reg.getOffset(); ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start); if (IJavaPartitions.JAVA_DOC.equals(region.getType())) start= d.getLineInformationOfOffset(region.getOffset()).getOffset(); if (getBracketCount(d, start, c.offset, true) > 0 && closeBrace() && !isClosed(d, c.offset, c.length)) { c.caretOffset= c.offset + buf.length(); c.shiftsCaret= false; // copy old content of line behind insertion point to new line // unless we think we are inserting an anonymous type definition if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) { if (lineEnd - contentStart > 0) { c.length= lineEnd - c.offset; buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray()); } } buf.append(getLineDelimiter(d)); String reference= indenter.getReferenceIndentation(c.offset); buf.append(reference == null ? "" : reference); //$NON-NLS-1$ buf.append('}'); } c.text= buf.toString(); } catch (BadLocationException e) { JavaPlugin.log(e); } } /** * Computes an insert position for an opening brace if <code>offset</code> maps to a position in * <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis. * * @param document the document being modified * @param offset the offset of the caret position, relative to the line start. * @param partitioning the document partitioning * @param max the max position * @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise */ private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) { // find the opening parenthesis for every closing parenthesis on the current line after offset // return the position behind the closing parenthesis if it looks like a method declaration // or an expression for an if, while, for, catch statement JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); int pos= offset; int length= max; int scanTo= scanner.scanForward(pos, length, '}'); if (scanTo == -1) scanTo= length; int closingParen= findClosingParenToLeft(scanner, pos) - 1; while (true) { int startScan= closingParen + 1; closingParen= scanner.scanForward(startScan, scanTo, ')'); if (closingParen == -1) break; int openingParen= scanner.findOpeningPeer(closingParen - 1, '(', ')'); // no way an expression at the beginning of the document can mean anything if (openingParen < 1) break; // only select insert positions for parenthesis currently embracing the caret if (openingParen > pos) continue; if (looksLikeAnonymousClassDef(document, partitioning, scanner, openingParen - 1)) return closingParen + 1; } return -1; } /** * Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only * separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found */ private static int findClosingParenToLeft(JavaHeuristicScanner scanner, int position) { if (position < 1) return position; if (scanner.previousToken(position - 1, JavaHeuristicScanner.UNBOUND) == Symbols.TokenRPAREN) return scanner.getPosition() + 1; return position; } /** * Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>) * contains the <code>new</code> keyword. * * @param document the document being modified * @param offset the first character position in <code>document</code> to be considered * @param length the length of the character range to be considered * @param partitioning the document partitioning * @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise. */ private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) { Assert.isTrue(length >= 0); Assert.isTrue(offset >= 0); Assert.isTrue(offset + length < document.getLength() + 1); try { String text= document.get(offset, length); int pos= text.indexOf("new"); //$NON-NLS-1$ while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning)) pos= text.indexOf("new", pos + 2); //$NON-NLS-1$ if (pos < 0) return false; if (pos != 0 && Character.isJavaIdentifierPart(document.getChar(pos - 1))) return false; if (pos + 3 < length && Character.isJavaIdentifierPart(document.getChar(pos + 3))) return false; return true; } catch (BadLocationException e) { } return false; } /** * Checks whether the content of <code>document</code> at <code>position</code> looks like an * anonymous class definition. <code>position</code> must be to the left of the opening * parenthesis of the definition's parameter list. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise */ private static boolean looksLikeAnonymousClassDef(IDocument document, String partitioning, JavaHeuristicScanner scanner, int position) { int previousCommaOrParen= scanner.scanBackward(position - 1, JavaHeuristicScanner.UNBOUND, new char[] {',', '('}); if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new" return false; if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning)) return true; return false; } /** * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>. * * @param document the document being modified * @param position the position to be checked * @param partitioning the document partitioning * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise */ private static boolean isDefaultPartition(IDocument document, int position, String partitioning) { Assert.isTrue(position >= 0); Assert.isTrue(position <= document.getLength()); try { ITypedRegion region= TextUtilities.getPartition(document, partitioning, position); return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE); } catch (BadLocationException e) { } return false; } private boolean isClosed(IDocument document, int offset, int length) { CompilationUnitInfo info= getCompilationUnitForMethod(document, offset, fPartitioning); if (info == null) return false; CompilationUnit compilationUnit= null; try { compilationUnit= AST.parseCompilationUnit(info.buffer); } catch (ArrayIndexOutOfBoundsException x) { // work around for parser problem return false; } IProblem[] problems= compilationUnit.getProblems(); for (int i= 0; i != problems.length; ++i) { if (problems[i].getID() == IProblem.UnmatchedBracket) return true; } final int relativeOffset= offset - info.delta; ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length); if (node == null) return false; if (length == 0) { while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength())) node= node.getParent(); } switch (node.getNodeType()) { case ASTNode.BLOCK: return areBlocksConsistent(document, offset, fPartitioning); case ASTNode.IF_STATEMENT: { IfStatement ifStatement= (IfStatement) node; Expression expression= ifStatement.getExpression(); IRegion expressionRegion= createRegion(expression, info.delta); Statement thenStatement= ifStatement.getThenStatement(); IRegion thenRegion= createRegion(thenStatement, info.delta); // between expression and then statement if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset()) return thenStatement != null; Statement elseStatement= ifStatement.getElseStatement(); IRegion elseRegion= createRegion(elseStatement, info.delta); IRegion elseToken= null; if (elseStatement != null) { int sourceOffset= thenRegion.getOffset() + thenRegion.getLength(); int sourceLength= elseRegion.getOffset() - sourceOffset; elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse); } // between 'else' keyword and else statement if (elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset()) return elseStatement != null; } break; case ASTNode.WHILE_STATEMENT: case ASTNode.FOR_STATEMENT: { Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression(); IRegion expressionRegion= createRegion(expression, info.delta); Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody(); IRegion bodyRegion= createRegion(body, info.delta); // between expression and body statement if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset()) return body != null; } break; case ASTNode.DO_STATEMENT: { DoStatement doStatement= (DoStatement) node; IRegion doRegion= createRegion(doStatement, info.delta); Statement body= doStatement.getBody(); IRegion bodyRegion= createRegion(body, info.delta); if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset()) return body != null; } break; } return true; } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { JavaPlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } private static boolean startsWithClosingBrace(String string) { final int length= string.length(); int i= 0; while (i != length && Character.isWhitespace(string.charAt(i))) ++i; if (i == length) return false; return string.charAt(i) == '}'; } private void smartPaste(IDocument document, DocumentCommand command) { String lineDelimiter= getLineDelimiter(document); try { String pastedText= command.text; Assert.isNotNull(pastedText); Assert.isTrue(pastedText.length() > 1); // extend selection begin if only whitespaces int selectionStart= command.offset; IRegion region= document.getLineInformationOfOffset(selectionStart); String notSelected= document.get(region.getOffset(), selectionStart - region.getOffset()); String selected= document.get(selectionStart, region.getOffset() + region.getLength() - selectionStart); if (notSelected.trim().length() == 0 && selected.trim().length() != 0) { pastedText= notSelected + pastedText; command.length += notSelected.length(); command.offset= region.getOffset(); } // choose smaller indent of block and preceeding non-empty line String blockIndent= getBlockIndent(document, command); String insideBlockIndent= blockIndent == null ? "" : blockIndent + createIndent(1, useSpaces()); //$NON-NLS-1$ // add one indent level int insideBlockIndentSize= calculateDisplayedWidth(insideBlockIndent, getTabWidth()); int previousIndentSize= getIndentSize(document, command); int newIndentSize= insideBlockIndentSize < previousIndentSize ? insideBlockIndentSize : previousIndentSize; // indent is different if block starts with '}' if (startsWithClosingBrace(pastedText)) { int outsideBlockIndentSize= blockIndent == null ? 0 : calculateDisplayedWidth(blockIndent, getTabWidth()); newIndentSize = outsideBlockIndentSize; } // check selection int offset= command.offset; int line= document.getLineOfOffset(offset); int lineOffset= document.getLineOffset(line); String prefix= document.get(lineOffset, offset - lineOffset); boolean formatFirstLine= prefix.trim().length() == 0; String formattedParagraph= format(pastedText, newIndentSize, lineDelimiter, formatFirstLine); // paste if (formatFirstLine) { int end= command.offset + command.length; command.offset= lineOffset; command.length= end - command.offset; } command.text= formattedParagraph; } catch (BadLocationException e) { JavaPlugin.log(e); } } private static String getIndentOfLine(String line) { int i= 0; for (; i < line.length(); i++) { if (! Character.isWhitespace(line.charAt(i))) break; } return line.substring(0, i); } /** * Returns the indent of the first non empty line. * A line is considered empty if it only consists of whitespaces or if it * begins with a single line comment followed by whitespaces only. */ private static int getIndentSizeOfFirstLine(String paragraph, boolean includeFirstLine, int tabWidth) { for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { final String line= (String) iterator.next(); if (!includeFirstLine) { includeFirstLine= true; continue; } String indent= null; if (line.startsWith(COMMENT)) { String commentedLine= line.substring(2); // line is empty if (commentedLine.trim().length() == 0) continue; indent= COMMENT + getIndentOfLine(commentedLine); } else { // line is empty if (line.trim().length() == 0) continue; indent= getIndentOfLine(line); } return calculateDisplayedWidth(indent, tabWidth); } return 0; } /** * Returns the minimal indent size of all non empty lines; */ private static int getMinimalIndentSize(String paragraph, boolean includeFirstLine, int tabWidth) { int minIndentSize= Integer.MAX_VALUE; for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { final String line= (String) iterator.next(); if (!includeFirstLine) { includeFirstLine= true; continue; } String indent= null; if (line.startsWith(COMMENT)) { String commentedLine= line.substring(2); // line is empty if (commentedLine.trim().length() == 0) continue; indent= COMMENT + getIndentOfLine(commentedLine); } else { // line is empty if (line.trim().length() == 0) continue; indent=getIndentOfLine(line); } final int indentSize= calculateDisplayedWidth(indent, tabWidth); if (indentSize < minIndentSize) minIndentSize= indentSize; } return minIndentSize == Integer.MAX_VALUE ? 0 : minIndentSize; } /** * Returns the displayed width of a string, taking in account the displayed tab width. * The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string, int tabWidth) { int column= 0; for (int i= 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else column++; return column; } private static boolean isLineEmpty(IDocument document, int line) throws BadLocationException { IRegion region= document.getLineInformation(line); String string= document.get(region.getOffset(), region.getLength()); return string.trim().length() == 0; } private int getIndentSize(IDocument document, DocumentCommand command) { StringBuffer buffer= new StringBuffer(); int docLength= document.getLength(); if (command.offset == -1 || docLength == 0) return 0; try { int p= (command.offset == docLength ? command.offset - 1 : command.offset); int line= document.getLineOfOffset(p); IRegion region= document.getLineInformation(line); String string= document.get(region.getOffset(), command.offset - region.getOffset()); if (line != 0 && string.trim().length() == 0) --line; while (line != 0 && isLineEmpty(document, line)) --line; int start= document.getLineOffset(line); // if line is at end of a javadoc comment, take the indent from the comment's begin line ITypedRegion typedRegion= TextUtilities.getPartition(document, fPartitioning, start); if (IJavaPartitions.JAVA_DOC.equals(typedRegion.getType())) { start= document.getLineInformationOfOffset(typedRegion.getOffset()).getOffset(); } else if (IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(typedRegion.getType())) { buffer.append(COMMENT); start += 2; } int whiteend= findEndOfWhiteSpace(document, start, command.offset); buffer.append(document.get(start, Math.max(whiteend - start, 0))); if (getBracketCount(document, start, command.offset, true) > 0) { buffer.append(createIndent(1, useSpaces())); } } catch (BadLocationException e) { JavaPlugin.log(e); } return calculateDisplayedWidth(buffer.toString(), getTabWidth()); } private String getBlockIndent(IDocument d, DocumentCommand c) { if (c.offset < 0 || d.getLength() == 0) return null; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1) // take the indent of the found line return getIndentOfLine(d, indLine); } catch (BadLocationException e) { JavaPlugin.log(e); } return null; } private String createIndent(int level, boolean useSpaces) { StringBuffer buffer= new StringBuffer(); if (useSpaces) { // Fix for bug 29909 contributed by Nikolay Metchev int width= level * getTabWidth(); for (int i= 0; i != width; ++i) buffer.append(' '); } else { for (int i= 0; i != level; ++i) buffer.append('\t'); } return buffer.toString(); } /** * Extends the string to match displayed width. * String is either the empty string or "//" and should not contain whites. */ private static String changePrefix(String string, int displayedWidth, boolean useSpaces, int tabWidth) { // assumption: string contains no whitespace final StringBuffer buffer= new StringBuffer(string); int column= calculateDisplayedWidth(buffer.toString(), tabWidth); if (column > displayedWidth) return string; if (useSpaces) { while (column != displayedWidth) { buffer.append(' '); ++column; } } else { while (column != displayedWidth) { if (column + tabWidth - (column % tabWidth) <= displayedWidth) { buffer.append('\t'); column += tabWidth - (column % tabWidth); } else { buffer.append(' '); ++column; } } } return buffer.toString(); } /** * Formats a paragraph such that the first non-empty line of the paragraph * will have an indent of size newIndentSize. */ private String format(String paragraph, int newIndentSize, String lineDelimiter, boolean indentFirstLine) { final int tabWidth= getTabWidth(); final int firstLineIndentSize= getIndentSizeOfFirstLine(paragraph, indentFirstLine, tabWidth); final int minIndentSize= getMinimalIndentSize(paragraph, indentFirstLine, tabWidth); if (newIndentSize < firstLineIndentSize - minIndentSize) newIndentSize= firstLineIndentSize - minIndentSize; final StringBuffer buffer= new StringBuffer(); for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); if (indentFirstLine) { String lineIndent= null; if (line.startsWith(COMMENT)) lineIndent= COMMENT + getIndentOfLine(line.substring(2)); else lineIndent= getIndentOfLine(line); String lineContent= line.substring(lineIndent.length()); if (lineContent.length() == 0) { // line was empty; insert as is buffer.append(line); } else { int indentSize= calculateDisplayedWidth(lineIndent, tabWidth); int deltaSize= newIndentSize - firstLineIndentSize; lineIndent= changePrefix(lineIndent.trim(), indentSize + deltaSize, useSpaces(), tabWidth); buffer.append(lineIndent); buffer.append(lineContent); } } else { indentFirstLine= true; buffer.append(line); } if (iterator.hasNext()) buffer.append(lineDelimiter); } return buffer.toString(); } private boolean isLineDelimiter(IDocument document, String text) { String[] delimiters= document.getLegalLineDelimiters(); if (delimiters != null) return TextUtilities.equals(delimiters, text) > -1; return false; } private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) { if (command.text.charAt(0) == '}') smartIndentAfterClosingBracket(document, command); else if (command.text.charAt(0) == '{') smartIndentAfterOpeningBracket(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) { clearCachedValues(); if (!isSmartMode() || c.doit == false) return; if (c.length == 0 && c.text != null && isLineDelimiter(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 IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } private boolean useSpaces() { return fUseSpaces; } private boolean closeBrace() { return fCloseBrace; } private int getTabWidth() { return fTabWidth; } private boolean isSmartMode() { return fIsSmartMode; } private void clearCachedValues() { // Fix for bug 29909 contributed by Nikolay Metchev fTabWidth= CodeFormatterUtil.getTabWidth(); IPreferenceStore preferenceStore= getPreferenceStore(); fUseSpaces= preferenceStore.getBoolean(PreferenceConstants.EDITOR_SPACES_FOR_TABS); fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES); fIsSmartMode= computeSmartMode(); } private boolean computeSmartMode() { IWorkbenchPage page= JavaPlugin.getActivePage(); if (page != null) { IEditorPart part= page.getActiveEditor(); if (part instanceof ITextEditorExtension3) { ITextEditorExtension3 extension= (ITextEditorExtension3) part; return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; } } return false; } private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset, String partitioning) { try { JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); IRegion sourceRange= scanner.findSurroundingBlock(offset); if (sourceRange == null) return null; String source= document.get(sourceRange.getOffset(), sourceRange.getLength()); StringBuffer contents= new StringBuffer(); contents.append("class ____C{void ____m()"); //$NON-NLS-1$ final int methodOffset= contents.length(); contents.append(source); contents.append('}'); char[] buffer= contents.toString().toCharArray(); return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset); } catch (BadLocationException e) { JavaPlugin.log(e); } return null; } private static boolean areBlocksConsistent(IDocument document, int offset, String partitioning) { if (offset < 1 || offset >= document.getLength()) return false; int begin= offset; int end= offset - 1; JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); while (true) { begin= scanner.findOpeningPeer(begin - 1, '{', '}'); end= scanner.findClosingPeer(end + 1, '{', '}'); if (begin == -1 && end == -1) return true; if (begin == -1 || end == -1) return false; } } private static IRegion createRegion(ASTNode node, int delta) { return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength()); } private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) { try { final String source= document.get(scanRegion.getOffset(), scanRegion.getLength()); IScanner scanner= ToolFactory.createScanner(false, false, false, false); scanner.setSource(source.toCharArray()); int id= scanner.getNextToken(); while (id != ITerminalSymbols.TokenNameEOF && id != tokenId) id= scanner.getNextToken(); if (id == ITerminalSymbols.TokenNameEOF) return null; int tokenOffset= scanner.getCurrentTokenStartPosition(); int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end return new Region(tokenOffset + scanRegion.getOffset(), tokenLength); } catch (InvalidInputException x) { return null; } catch (BadLocationException x) { return null; } } }
44,413
Bug 44413 [misc] Exception while deleting a project
20031008 smoke After the smoke, I wanted to remove the project but this failed: The project was not removed. Java Model Exception: Java Model Status [junit.tests [in <project root> [in JUnit]] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:476) at org.eclipse.jdt.internal.core.PackageFragment.buildStructure (PackageFragment.java:61) at org.eclipse.jdt.internal.core.Openable.generateInfos (Openable.java:200) at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed (JavaElement.java:487) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:278) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:264) at org.eclipse.jdt.internal.core.JavaElement.getChildren (JavaElement.java:219) at org.eclipse.jdt.internal.core.Openable.hasChildren(Openable.java:302) at org.eclipse.jdt.ui.StandardJavaElementContentProvider.isPackageFragmentEmpty (StandardJavaElementContentProvider.java:370) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:314) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.elementCh anged(PackageExplorerContentProvider.java:75) at org.eclipse.jdt.internal.core.DeltaProcessor$2.run (DeltaProcessor.java:1387) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1034) at org.eclipse.core.runtime.Platform.run(Platform.java:432) at org.eclipse.jdt.internal.core.DeltaProcessor.notifyListeners (DeltaProcessor.java:1382) at org.eclipse.jdt.internal.core.DeltaProcessor.firePostChangeDelta (DeltaProcessor.java:1226) at org.eclipse.jdt.internal.core.DeltaProcessor.fire (DeltaProcessor.java:1201) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:725) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.java:523) at org.eclipse.jdt.internal.core.CompilationUnit.discardWorkingCopy (CompilationUnit.java:375) at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CompilationUnitDocumentProvid er2.disposeFileInfo(CompilationUnitDocumentProvider2.java:794) at org.eclipse.ui.editors.text.TextFileDocumentProvider.disconnect (TextFileDocumentProvider.java:435) at org.eclipse.ui.texteditor.AbstractTextEditor.dispose (AbstractTextEditor.java:2636) at org.eclipse.ui.texteditor.ExtendedTextEditor.dispose (ExtendedTextEditor.java:177) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.dispose (JavaEditor.java:2139) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.dispose (CompilationUnitEditor.java:1065) at org.eclipse.ui.internal.WorkbenchPartReference.dispose (WorkbenchPartReference.java:160) at org.eclipse.ui.internal.EditorManager$Editor.dispose (EditorManager.java:1322) at org.eclipse.ui.internal.WorkbenchPage$5.run(WorkbenchPage.java:1046) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1034) at org.eclipse.core.runtime.Platform.run(Platform.java:432) at org.eclipse.ui.internal.WorkbenchPage.disposePart (WorkbenchPage.java:1044) at org.eclipse.ui.internal.WorkbenchPage.closeEditor (WorkbenchPage.java:850) at org.eclipse.ui.texteditor.AbstractTextEditor$15.run (AbstractTextEditor.java:2539) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:102) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:2150) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1867) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block (ModalContext.java:136) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:261) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run (ProgressMonitorDialog.java:386) at org.eclipse.ui.actions.DeleteResourceAction.run (DeleteResourceAction.java:388) at org.eclipse.jdt.internal.ui.refactoring.reorg.DeleteAction.run (DeleteAction.java:87) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:194) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup.handleKeyEven t(PackageExplorerActionGroup.java:332) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$9.keyReleased (PackageExplorerPart.java:923) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:124) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1689) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1685) at org.eclipse.swt.widgets.Control.WM_KEYUP(Control.java:3514) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2916) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2698) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1345) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1861) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2315) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2298) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:298) at org.eclipse.core.launcher.Main.run(Main.java:764) at org.eclipse.core.launcher.Main.main(Main.java:598)
resolved fixed
ab08077
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-13T14:28:23Z
2003-10-08T10:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerContentProvider.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jdt.core.*; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; 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 { private TreeViewer fViewer; private Object fInput; private boolean fIsFlatLayout; private PackageFragmentProvider fPackageFragmentProvider= new PackageFragmentProvider(); private int fPendingChanges; private PackageExplorerPart fPart; /** * Creates a new content provider for Java elements. */ public PackageExplorerContentProvider(PackageExplorerPart part, boolean provideMembers, boolean provideWorkingCopy) { super(provideMembers, provideWorkingCopy); fPart= part; } /* (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 needsToDelegateGetChildren(Object element) { int type= -1; if (element instanceof IJavaElement) type= ((IJavaElement)element).getElementType(); return (!fIsFlatLayout && (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.JAVA_PROJECT)); } public Object[] getChildren(Object parentElement) { Object[] children= NO_CHILDREN; try { if (parentElement instanceof IJavaModel) return concatenate(getJavaProjects((IJavaModel)parentElement), getNonJavaProjects((IJavaModel)parentElement)); if (parentElement instanceof ClassPathContainer) return getContainerPackageFragmentRoots((ClassPathContainer)parentElement); if (parentElement instanceof IProject) return ((IProject)parentElement).members(); if (needsToDelegateGetChildren(parentElement)) { Object[] packageFragments= fPackageFragmentProvider.getChildren(parentElement); children= getWithParentsResources(packageFragments, parentElement); } else { children= super.getChildren(parentElement); } if (parentElement instanceof IJavaProject) { IJavaProject project= (IJavaProject)parentElement; return rootsAndContainers(project, children); } else return children; } catch (CoreException e) { return NO_CHILDREN; } } private Object[] rootsAndContainers(IJavaProject project, Object[] roots) throws JavaModelException { List result= new ArrayList(roots.length); Set containers= new HashSet(roots.length); Set containedRoots= new HashSet(roots.length); IClasspathEntry[] entries= project.getRawClasspath(); for (int i= 0; i < entries.length; i++) { IClasspathEntry entry= entries[i]; if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IPackageFragmentRoot[] roots1= project.findPackageFragmentRoots(entry); containedRoots.addAll(Arrays.asList(roots1)); containers.add(entry); } } for (int i= 0; i < roots.length; i++) { if (roots[i] instanceof IPackageFragmentRoot) { if (!containedRoots.contains(roots[i])) { result.add(roots[i]); } } else { result.add(roots[i]); } } for (Iterator each= containers.iterator(); each.hasNext();) { IClasspathEntry element= (IClasspathEntry) each.next(); result.add(new ClassPathContainer(project, element)); } return result.toArray(); } private Object[] getContainerPackageFragmentRoots(ClassPathContainer container) throws JavaModelException { return container.getPackageFragmentRoots(); } private Object[] getNonJavaProjects(IJavaModel model) throws JavaModelException { return model.getNonJavaResources(); } public Object getParent(Object child) { if (needsToDelegateGetParent(child)) { return fPackageFragmentProvider.getParent(child); } else return super.getParent(child); } protected Object internalGetParent(Object element) { // since we insert logical package containers we have to fix // up the parent for package fragment roots so that they refer // to the container and containers refere to the project // if (element instanceof IPackageFragmentRoot) { IPackageFragmentRoot root= (IPackageFragmentRoot)element; IJavaProject project= root.getJavaProject(); try { IClasspathEntry[] entries= project.getRawClasspath(); for (int i= 0; i < entries.length; i++) { IClasspathEntry entry= entries[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { if (ClassPathContainer.contains(project, entry, root)) return new ClassPathContainer(project, entry); } } } catch (JavaModelException e) { // fall through } } if (element instanceof ClassPathContainer) { return ((ClassPathContainer)element).getJavaProject(); } return super.internalGetParent(element); } private boolean needsToDelegateGetParent(Object element) { int type= -1; if (element instanceof IJavaElement) type= ((IJavaElement)element).getElementType(); return (!fIsFlatLayout && type == IJavaElement.PACKAGE_FRAGMENT); } /** * 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. */ private void processDelta(IJavaElementDelta delta) throws JavaModelException { int kind= delta.getKind(); int flags= delta.getFlags(); IJavaElement element= delta.getElement(); int elementType= element.getElementType(); if (elementType != IJavaElement.JAVA_MODEL && elementType != IJavaElement.JAVA_PROJECT) { IJavaProject proj= element.getJavaProject(); if (proj == null || !proj.getProject().isOpen()) // TODO: Not needed if parent already did the 'open' check! return; } if (!fIsFlatLayout && elementType == IJavaElement.PACKAGE_FRAGMENT) { fPackageFragmentProvider.processDelta(delta); if (processResourceDeltas(delta.getResourceDeltas(), element)) return; IJavaElementDelta[] affectedChildren= delta.getAffectedChildren(); processAffectedChildren(affectedChildren); return; } if (elementType == IJavaElement.COMPILATION_UNIT) { ICompilationUnit cu= (ICompilationUnit) element; if (!JavaModelUtil.isPrimary(cu)) { return; } if (!getProvideWorkingCopy() && cu.isWorkingCopy()) { return; } if ((kind == IJavaElementDelta.CHANGED) && !isStructuralCUChange(flags)) { return; // test moved ahead } if (!isOnClassPath(cu)) { // TODO: isOnClassPath expensive! Should be put after all cheap tests return; } if (!JavaPlugin.USE_WORKING_COPY_OWNERS && cu.isWorkingCopy()) { if (kind == IJavaElementDelta.REMOVED || kind == IJavaElementDelta.ADDED) { // switch between original and working copy or vice versa postRefresh(JavaModelUtil.toOriginal(cu), false); return; } } } if (elementType == IJavaElement.JAVA_PROJECT) { // handle open and closing of a project if ((flags & (IJavaElementDelta.F_CLOSED | IJavaElementDelta.F_OPENED)) != 0) { postRefresh(element); return; } } if (kind == IJavaElementDelta.REMOVED) { 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) { Object parent= internalGetParent(element); // we are filtering out empty subpackages, so we // have to handle additions to them specially. if (parent instanceof IPackageFragment) { Object grandparent= internalGetParent(parent); // 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View // avoid posting a refresh to an unvisible parent if (parent.equals(fInput)) { postRefresh(parent); } else { // refresh from grandparent if parent isn't visible yet if (fViewer.testFindItem(parent) == null) postRefresh(grandparent); else { postRefresh(parent); } } return; } else { postAdd(parent, element); } } if (elementType == IJavaElement.COMPILATION_UNIT) { if (kind == IJavaElementDelta.CHANGED) { // isStructuralCUChange already performed above element= JavaModelUtil.toOriginal((ICompilationUnit) element); postRefresh(element); updateSelection(delta); } return; } // no changes possible in class files if (elementType == IJavaElement.CLASS_FILE) return; if (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT) { // the contents of an external JAR has changed if ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) { postRefresh(element); return; } // the source attachment of a JAR has changed if ((flags & (IJavaElementDelta.F_SOURCEATTACHED | IJavaElementDelta.F_SOURCEDETACHED)) != 0) postUpdateIcon(element); if (isClassPathChange(delta)) { // throw the towel and do a full refresh of the affected java project. postRefresh(element.getJavaProject()); return; } } if (processResourceDeltas(delta.getResourceDeltas(), element)) return; handleAffectedChildren(delta, element); } private static boolean isStructuralCUChange(int flags) { // No refresh on working copy creation (F_PRIMARY_WORKING_COPY) return ((flags & IJavaElementDelta.F_CHILDREN) != 0) || ((flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT); } 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; } /** * Updates the package icon */ private void postUpdateIcon(final IJavaElement element) { postRunnable(new Runnable() { public void run() { // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE}); } }); } /** 1 * Process a resource delta. * * @return true if the parent got refreshed */ private boolean processResourceDelta(IResourceDelta delta, Object parent) { int status= delta.getKind(); int flags= delta.getFlags(); IResource resource= delta.getResource(); // filter out changes affecting the output folder if (resource == null) return false; // this could be optimized by handling all the added children in the parent if ((status & IResourceDelta.REMOVED) != 0) { if (parent instanceof IPackageFragment) { // refresh one level above to deal with empty package filtering properly postRefresh(internalGetParent(parent)); return true; } else postRemove(resource); } if ((status & IResourceDelta.ADDED) != 0) { if (parent instanceof IPackageFragment) { // refresh one level above to deal with empty package filtering properly postRefresh(internalGetParent(parent)); return true; } else postAdd(parent, resource); } // open/close state change of a project if ((flags & IResourceDelta.OPEN) != 0) { postProjectStateChanged(internalGetParent(parent)); return true; } processResourceDeltas(delta.getAffectedChildren(), resource); return false; } void setIsFlatLayout(boolean state) { fIsFlatLayout= state; } /** * Process resource deltas. * * @return true if the parent got refreshed */ private boolean processResourceDeltas(IResourceDelta[] deltas, Object parent) { if (deltas == null) return false; if (deltas.length > 1) { // more than one child changed, refresh from here downwards postRefresh(parent); return true; } for (int i= 0; i < deltas.length; i++) { if (processResourceDelta(deltas[i], parent)) return true; } return false; } private void postRefresh(Object root) { // JFace doesn't refresh when object isn't part of the viewer // Therefore move the refresh start down to the viewer's input if (isParent(root, fInput)) root= fInput; postRefresh(root, true); } boolean isParent(Object root, Object child) { Object parent= getParent(child); if (parent == null) return false; if (parent.equals(root)) return true; return isParent(root, parent); } private void postRefresh(final Object root, final boolean updateLabels) { postRunnable(new Runnable() { public void run() { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()){ fViewer.refresh(root, updateLabels); } } }); } private void postAdd(final Object parent, final Object element) { postRunnable(new Runnable() { public void run() { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()){ // TODO workaround for 39754 New projects being added to the TreeViewer twice if (fViewer.testFindItem(element) == null) fViewer.add(parent, element); } } }); } private void postRemove(final Object element) { postRunnable(new Runnable() { public void run() { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { fViewer.remove(element); } } }); } private void postProjectStateChanged(final Object root) { postRunnable(new Runnable() { public void run() { fPart.projectStateChanged(root); } }); } private void postRunnable(final Runnable r) { Control ctrl= fViewer.getControl(); final Runnable trackedRunnable= new Runnable() { public void run() { try { r.run(); } finally { removePendingChange(); } } }; if (ctrl != null && !ctrl.isDisposed()) { addPendingChange(); try { ctrl.getDisplay().asyncExec(trackedRunnable); } catch (RuntimeException e) { removePendingChange(); throw e; } catch (Error e) { removePendingChange(); throw e; } } } // ------ Pending change management due to the use of asyncExec in postRunnable. public synchronized boolean hasPendingChanges() { return fPendingChanges > 0; } private synchronized void addPendingChange() { fPendingChanges++; // System.out.print(fPendingChanges); } private synchronized void removePendingChange() { fPendingChanges--; if (fPendingChanges < 0) fPendingChanges= 0; // System.out.print(fPendingChanges); } }
44,413
Bug 44413 [misc] Exception while deleting a project
20031008 smoke After the smoke, I wanted to remove the project but this failed: The project was not removed. Java Model Exception: Java Model Status [junit.tests [in <project root> [in JUnit]] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:476) at org.eclipse.jdt.internal.core.PackageFragment.buildStructure (PackageFragment.java:61) at org.eclipse.jdt.internal.core.Openable.generateInfos (Openable.java:200) at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed (JavaElement.java:487) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:278) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:264) at org.eclipse.jdt.internal.core.JavaElement.getChildren (JavaElement.java:219) at org.eclipse.jdt.internal.core.Openable.hasChildren(Openable.java:302) at org.eclipse.jdt.ui.StandardJavaElementContentProvider.isPackageFragmentEmpty (StandardJavaElementContentProvider.java:370) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:314) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processAf fectedChildren(PackageExplorerContentProvider.java:416) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.handleAff ectedChildren(PackageExplorerContentProvider.java:411) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.processDe lta(PackageExplorerContentProvider.java:379) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.elementCh anged(PackageExplorerContentProvider.java:75) at org.eclipse.jdt.internal.core.DeltaProcessor$2.run (DeltaProcessor.java:1387) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1034) at org.eclipse.core.runtime.Platform.run(Platform.java:432) at org.eclipse.jdt.internal.core.DeltaProcessor.notifyListeners (DeltaProcessor.java:1382) at org.eclipse.jdt.internal.core.DeltaProcessor.firePostChangeDelta (DeltaProcessor.java:1226) at org.eclipse.jdt.internal.core.DeltaProcessor.fire (DeltaProcessor.java:1201) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:725) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.java:523) at org.eclipse.jdt.internal.core.CompilationUnit.discardWorkingCopy (CompilationUnit.java:375) at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CompilationUnitDocumentProvid er2.disposeFileInfo(CompilationUnitDocumentProvider2.java:794) at org.eclipse.ui.editors.text.TextFileDocumentProvider.disconnect (TextFileDocumentProvider.java:435) at org.eclipse.ui.texteditor.AbstractTextEditor.dispose (AbstractTextEditor.java:2636) at org.eclipse.ui.texteditor.ExtendedTextEditor.dispose (ExtendedTextEditor.java:177) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.dispose (JavaEditor.java:2139) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.dispose (CompilationUnitEditor.java:1065) at org.eclipse.ui.internal.WorkbenchPartReference.dispose (WorkbenchPartReference.java:160) at org.eclipse.ui.internal.EditorManager$Editor.dispose (EditorManager.java:1322) at org.eclipse.ui.internal.WorkbenchPage$5.run(WorkbenchPage.java:1046) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1034) at org.eclipse.core.runtime.Platform.run(Platform.java:432) at org.eclipse.ui.internal.WorkbenchPage.disposePart (WorkbenchPage.java:1044) at org.eclipse.ui.internal.WorkbenchPage.closeEditor (WorkbenchPage.java:850) at org.eclipse.ui.texteditor.AbstractTextEditor$15.run (AbstractTextEditor.java:2539) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:102) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:2150) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1867) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block (ModalContext.java:136) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:261) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run (ProgressMonitorDialog.java:386) at org.eclipse.ui.actions.DeleteResourceAction.run (DeleteResourceAction.java:388) at org.eclipse.jdt.internal.ui.refactoring.reorg.DeleteAction.run (DeleteAction.java:87) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:194) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup.handleKeyEven t(PackageExplorerActionGroup.java:332) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$9.keyReleased (PackageExplorerPart.java:923) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:124) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1689) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1685) at org.eclipse.swt.widgets.Control.WM_KEYUP(Control.java:3514) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2916) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2698) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1345) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1861) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2315) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2298) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:298) at org.eclipse.core.launcher.Main.run(Main.java:764) at org.eclipse.core.launcher.Main.main(Main.java:598)
resolved fixed
ab08077
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-13T14:28:23Z
2003-10-08T10:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/StandardJavaElementContentProvider.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; /** * A base content provider for Java elements. It provides access to the * Java element hierarchy without listening to changes in the Java model. * If updating the presentation on Java model change is required than * clients have to subclass, listen to Java model changes and have to update * the UI using corresponding methods provided by the JFace viewers or their * own UI presentation. * <p> * The following Java element hierarchy is surfaced by this content provider: * <p> * <pre> Java model (<code>IJavaModel</code>) Java project (<code>IJavaProject</code>) package fragment root (<code>IPackageFragmentRoot</code>) package fragment (<code>IPackageFragment</code>) compilation unit (<code>ICompilationUnit</code>) binary class file (<code>IClassFile</code>) * </pre> * </p> * <p> * Note that when the entire Java project is declared to be package fragment root, * the corresponding package fragment root element that normally appears between the * Java project and the package fragments is automatically filtered out. * </p> * This content provider can optionally return working copy elements for members * below compilation units. If enabled, working copy members are returned for those * compilation units in the Java element hierarchy for which a shared working copy exists * in JDT core. * * @see org.eclipse.jdt.ui.IWorkingCopyProvider * @see JavaCore#getSharedWorkingCopies(org.eclipse.jdt.core.IBufferFactory) * * @since 2.0 */ public class StandardJavaElementContentProvider implements ITreeContentProvider, IWorkingCopyProvider { protected static final Object[] NO_CHILDREN= new Object[0]; protected boolean fProvideMembers= false; protected boolean fProvideWorkingCopy= false; /** * Creates a new content provider. The content provider does not * provide members of compilation units or class files and it does * not provide working copy elements. */ public StandardJavaElementContentProvider() { } /** * Creates a new <code>StandardJavaElementContentProvider</code>. * * @param provideMembers if <code>true</code> members below compilation units * and class files are provided. * @param provideWorkingCopy if <code>true</code> the element provider provides * working copies members of compilation units which have an associated working * copy in JDT core. Otherwise only original elements are provided. */ public StandardJavaElementContentProvider(boolean provideMembers, boolean provideWorkingCopy) { fProvideMembers= provideMembers; fProvideWorkingCopy= provideWorkingCopy; } /** * Returns whether members are provided when asking * for a compilation units or class file for its children. * * @return <code>true</code> if the content provider provides members; * otherwise <code>false</code> is returned */ public boolean getProvideMembers() { return fProvideMembers; } /** * Sets whether the content provider is supposed to return members * when asking a compilation unit or class file for its children. * * @param b if <code>true</code> then members are provided. * If <code>false</code> compilation units and class files are the * leaves provided by this content provider. */ public void setProvideMembers(boolean b) { fProvideMembers= b; } /** * Returns whether the provided members are from a working * copy or the original compilation unit. * * @return <code>true</code> if the content provider provides * working copy members; otherwise <code>false</code> is * returned * * @see #setProvideWorkingCopy(boolean) */ public boolean getProvideWorkingCopy() { return fProvideWorkingCopy; } /** * Sets whether the members are provided from a shared working copy * that exists for a original compilation unit in the Java element hierarchy. * * @param b if <code>true</code> members are provided from a * working copy if one exists in JDT core. If <code>false</code> the * provider always returns original elements. */ public void setProvideWorkingCopy(boolean b) { fProvideWorkingCopy= b; } /* (non-Javadoc) * @see IWorkingCopyProvider#providesWorkingCopies() */ public boolean providesWorkingCopies() { return fProvideWorkingCopy; } /* (non-Javadoc) * Method declared on IStructuredContentProvider. */ public Object[] getElements(Object parent) { return getChildren(parent); } /* (non-Javadoc) * Method declared on IContentProvider. */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } /* (non-Javadoc) * Method declared on IContentProvider. */ public void dispose() { } /* (non-Javadoc) * Method declared on ITreeContentProvider. */ public Object[] getChildren(Object element) { if (!exists(element)) return NO_CHILDREN; try { if (element instanceof IJavaModel) return getJavaProjects((IJavaModel)element); if (element instanceof IJavaProject) return getPackageFragmentRoots((IJavaProject)element); if (element instanceof IPackageFragmentRoot) return getPackageFragments((IPackageFragmentRoot)element); if (element instanceof IPackageFragment) return getPackageContents((IPackageFragment)element); if (element instanceof IFolder) return getResources((IFolder)element); if (getProvideMembers() && element instanceof ISourceReference && element instanceof IParent) { if (getProvideWorkingCopy() && element instanceof ICompilationUnit) { element= JavaModelUtil.toWorkingCopy((ICompilationUnit) element); } return ((IParent)element).getChildren(); } } catch (JavaModelException e) { return NO_CHILDREN; } return NO_CHILDREN; } /* (non-Javadoc) * @see ITreeContentProvider */ public boolean hasChildren(Object element) { if (getProvideMembers()) { // assume CUs and class files are never empty if (element instanceof ICompilationUnit || element instanceof IClassFile) { return true; } } else { // don't allow to drill down into a compilation unit or class file if (element instanceof ICompilationUnit || element instanceof IClassFile || element instanceof IFile) return false; } if (element instanceof IJavaProject) { IJavaProject jp= (IJavaProject)element; if (!jp.getProject().isOpen()) { return false; } } if (element instanceof IParent) { try { // when we have Java children return true, else we fetch all the children if (((IParent)element).hasChildren()) return true; } catch(JavaModelException e) { return true; } } Object[] children= getChildren(element); return (children != null) && children.length > 0; } /* (non-Javadoc) * Method declared on ITreeContentProvider. */ public Object getParent(Object element) { if (!exists(element)) return null; return internalGetParent(element); } private Object[] getPackageFragments(IPackageFragmentRoot root) throws JavaModelException { IJavaElement[] fragments= root.getChildren(); Object[] nonJavaResources= root.getNonJavaResources(); if (nonJavaResources == null) return fragments; return concatenate(fragments, nonJavaResources); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException { if (!project.getProject().isOpen()) return NO_CHILDREN; IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); List list= new ArrayList(roots.length); // filter out package fragments that correspond to projects and // replace them with the package fragments directly for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot root= roots[i]; if (isProjectPackageFragmentRoot(root)) { Object[] children= root.getChildren(); for (int k= 0; k < children.length; k++) list.add(children[k]); } else if (hasChildren(root)) { list.add(root); } } return concatenate(list.toArray(), project.getNonJavaResources()); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object[] getJavaProjects(IJavaModel jm) throws JavaModelException { return jm.getJavaProjects(); } private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException { if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) { return concatenate(fragment.getCompilationUnits(), fragment.getNonJavaResources()); } return concatenate(fragment.getClassFiles(), fragment.getNonJavaResources()); } private Object[] getResources(IFolder folder) { try { // filter out folders that are package fragment roots Object[] members= folder.members(); List nonJavaResources= new ArrayList(); for (int i= 0; i < members.length; i++) { Object o= members[i]; // A folder can also be a package fragement root in the following case // Project // + src <- source folder // + excluded <- excluded from class path // + included <- a new source folder. // Included is a member of excluded, but since it is rendered as a source // folder we have to exclude it as a normal child. if (o instanceof IFolder) { IJavaElement element= JavaCore.create((IFolder)o); if (element instanceof IPackageFragmentRoot && element.exists()) { continue; } } nonJavaResources.add(o); } return nonJavaResources.toArray(); } catch(CoreException e) { return NO_CHILDREN; } } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean isClassPathChange(IJavaElementDelta delta) { // need to test the flags only for package fragment roots if (delta.getElement().getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) return false; int flags= delta.getFlags(); return (delta.getKind() == IJavaElementDelta.CHANGED && ((flags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) || ((flags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) || ((flags & IJavaElementDelta.F_REORDER) != 0)); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object skipProjectPackageFragmentRoot(IPackageFragmentRoot root) { try { if (isProjectPackageFragmentRoot(root)) return root.getParent(); return root; } catch(JavaModelException e) { return root; } } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean isPackageFragmentEmpty(IJavaElement element) throws JavaModelException { if (element instanceof IPackageFragment) { IPackageFragment fragment= (IPackageFragment)element; if (!(fragment.hasChildren() || fragment.getNonJavaResources().length > 0) && fragment.hasSubpackages()) return true; } return false; } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) throws JavaModelException { IResource resource= root.getResource(); return (resource instanceof IProject); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean exists(Object element) { if (element == null) { return false; } if (element instanceof IResource) { return ((IResource)element).exists(); } if (element instanceof IJavaElement) { return ((IJavaElement)element).exists(); } return true; } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object internalGetParent(Object element) { if (element instanceof IJavaProject) { return ((IJavaProject)element).getJavaModel(); } // try to map resources to the containing package fragment if (element instanceof IResource) { IResource parent= ((IResource)element).getParent(); IJavaElement jParent= JavaCore.create(parent); // http://bugs.eclipse.org/bugs/show_bug.cgi?id=31374 if (jParent != null && jParent.exists()) return jParent; return parent; } // for package fragments that are contained in a project package fragment // we have to skip the package fragment root as the parent. if (element instanceof IPackageFragment) { IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent(); return skipProjectPackageFragmentRoot(parent); } if (element instanceof IJavaElement) { IJavaElement candidate= ((IJavaElement)element).getParent(); // If the parent is a CU we might have shown working copy elements below CU level. If so // return the original element instead of the working copy. if (candidate != null && candidate.getElementType() == IJavaElement.COMPILATION_UNIT) { candidate= JavaModelUtil.toOriginal((ICompilationUnit) candidate); } return candidate; } return null; } /** * Note: This method is for internal use only. Clients should not call this method. */ protected static Object[] concatenate(Object[] a1, Object[] a2) { int a1Len= a1.length; int a2Len= a2.length; Object[] res= new Object[a1Len + a2Len]; System.arraycopy(a1, 0, res, 0, a1Len); System.arraycopy(a2, 0, res, a1Len, a2Len); return res; } }
44,721
Bug 44721 Source formatting is very slow
The code formatting of longer java source files in M4 is extremely slow.
resolved fixed
d038e84
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-13T15:21:30Z
2003-10-12T17:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentFormattingStrategy.java
/***************************************************************************** * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *****************************************************************************/ package org.eclipse.jdt.internal.ui.text.comment; import java.util.LinkedList; import java.util.Map; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.formatter.ContentFormatter; import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy; import org.eclipse.jface.text.formatter.FormattingContext; import org.eclipse.jface.text.formatter.FormattingContextProperties; import org.eclipse.jface.text.formatter.IFormattingContext; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; /** * Formatting strategy for general source code comments. * <p> * This strategy implements <code>IFormattingStrategyExtension</code>. It * must be registered with a content formatter implementing <code>IContentFormatterExtension2<code> * to take effect. * * @since 3.0 */ public class CommentFormattingStrategy extends ContextBasedFormattingStrategy { /** * Returns the indentation of the line at the specified offset. * * @param document * Document which owns the line * @param region * Comment region which owns the line * @param offset * Offset where to determine the indentation * @return The indentation of the line */ public static String getLineIndentation(final IDocument document, final CommentRegion region, final int offset) { String result= ""; //$NON-NLS-1$ try { final IRegion line= document.getLineInformationOfOffset(offset); final int begin= line.getOffset(); final int end= Math.min(offset, line.getOffset() + line.getLength()); result= region.stringToIndent(document.get(begin, end - begin), true); } catch (BadLocationException exception) { // Should not happen } return result; } /** * Content formatter with which this formatting strategy has been * registered */ private final ContentFormatter fFormatter; /** Partitions to be formatted by this strategy */ private final LinkedList fPartitions= new LinkedList(); /** * Creates a new comment formatting strategy. * * @param formatter * The content formatter with which this formatting strategy has * been registered * @param viewer * The source viewer where to apply the formatting strategy */ public CommentFormattingStrategy(final ContentFormatter formatter, final ISourceViewer viewer) { super(viewer); fFormatter= formatter; } /* * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format() */ public void format() { super.format(); Assert.isLegal(fPartitions.size() > 0); final IDocument document= getViewer().getDocument(); final TypedPosition position= (TypedPosition)fPartitions.removeFirst(); try { final ITypedRegion partition= TextUtilities.getPartition(document, fFormatter.getDocumentPartitioning(), position.getOffset()); final String type= partition.getType(); position.offset= partition.getOffset(); position.length= partition.getLength(); final Map preferences= getPreferences(); final boolean format= preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMAT) == IPreferenceStore.TRUE; final boolean header= preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER) == IPreferenceStore.TRUE; if (format && (header || position.getOffset() != 0 || !type.equals(IJavaPartitions.JAVA_DOC))) { final CommentRegion region= CommentObjectFactory.createRegion(this, position, TextUtilities.getDefaultLineDelimiter(document)); final String indentation= getLineIndentation(document, region, position.getOffset()); final Map partitioners= TextUtilities.removeDocumentPartitioners(document); region.format(indentation); TextUtilities.addDocumentPartitioners(document, partitioners); } } catch (BadLocationException exception) { // Should not happen } } /* * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext) */ public void formatterStarts(IFormattingContext context) { super.formatterStarts(context); final FormattingContext current= (FormattingContext)context; fPartitions.addLast(current.getProperty(FormattingContextProperties.CONTEXT_PARTITION)); } /* * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStops() */ public void formatterStops() { super.formatterStops(); fPartitions.clear(); } /** * Returns the content formatter with which this formatting strategy has * been registered. * * @return The content formatter */ public final ContentFormatter getFormatter() { return fFormatter; } }
44,668
Bug 44668 [Navigator] "Link with" button in Navigator doesn't scroll to current file if it's already selected
If you double-click on a file to open it, scroll the navigator so that you can no longer see the highlighted file, and then click on the "Link with" button in the toolbar menu, the navigator doesn't scroll to make the file visible. Clicking it repeatedly (to turn it off and on) doesn't scroll either. Intuitively one would expect that if linking is off and you click the button to turn it on, then the currently edited file should be made visible in the Navigator. Package Explorer works the same way.
resolved fixed
b15ae8b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-15T11:15:27Z
2003-10-10T15:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ITreeViewerListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeExpansionEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.part.ISetSelectionTarget; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTarget; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.FilterUpdater; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.ui.IPackagesViewPart; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; /** * The ViewPart for the ProjectExplorer. It listens to part activation events. * When selection linking with the editor is enabled the view selection tracks * the active editor page. Similarly when a resource is selected in the packages * view the corresponding editor is activated. */ public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IShowInTarget, IPackagesViewPart, IPropertyChangeListener, IViewPartInputProvider { private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical private static final int HIERARCHICAL_LAYOUT= 0x1; private static final int FLAT_LAYOUT= 0x2; public final static String VIEW_ID= JavaUI.ID_PACKAGES; // Persistance tags. static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$ static final String TAG_ELEMENT= "element"; //$NON-NLS-1$ static final String TAG_PATH= "path"; //$NON-NLS-1$ static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$ static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$ static final String TAG_FILTERS = "filters"; //$NON-NLS-1$ static final String TAG_FILTER = "filter"; //$NON-NLS-1$ static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$ private PackageExplorerContentProvider fContentProvider; private FilterUpdater fFilterUpdater; private PackageExplorerActionGroup fActionSet; private ProblemTreeViewer fViewer; private Menu fContextMenu; private IMemento fMemento; private ISelectionChangedListener fSelectionListener; private String fWorkingSetName; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; private ITreeViewerListener fExpansionListener= new ITreeViewerListener() { public void treeCollapsed(TreeExpansionEvent event) { } public void treeExpanded(TreeExpansionEvent event) { Object element= event.getElement(); if (element instanceof ICompilationUnit || element instanceof IClassFile) expandMainType(element); } }; private PackageExplorerLabelProvider fLabelProvider; /* (non-Javadoc) * Method declared on IViewPart. */ private boolean fLinkingEnabled; public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; restoreLayoutState(memento); } private void restoreLayoutState(IMemento memento) { Integer state= null; if (memento != null) state= memento.getInteger(TAG_LAYOUT); // If no memento try an restore from preference store if(state == null) { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); state= new Integer(store.getInt(TAG_LAYOUT)); } if (state.intValue() == FLAT_LAYOUT) fIsCurrentLayoutFlat= true; else if (state.intValue() == HIERARCHICAL_LAYOUT) fIsCurrentLayoutFlat= false; else fIsCurrentLayoutFlat= true; } /** * Returns the package explorer part of the active perspective. If * there isn't any package explorer part <code>null</code> is returned. */ public static PackageExplorerPart getFromActivePerspective() { IWorkbenchPage activePage= JavaPlugin.getActivePage(); if (activePage == null) return null; IViewPart view= activePage.findView(VIEW_ID); if (view instanceof PackageExplorerPart) return (PackageExplorerPart)view; return null; } /** * Makes the package explorer part visible in the active perspective. If there * isn't a package explorer part registered <code>null</code> is returned. * Otherwise the opened view part is returned. */ public static PackageExplorerPart openInActivePerspective() { try { return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID); } catch(PartInitException pe) { return null; } } public void dispose() { if (fContextMenu != null && !fContextMenu.isDisposed()) fContextMenu.dispose(); getSite().getPage().removePartListener(fPartListener); JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); if (fViewer != null) fViewer.removeTreeListener(fExpansionListener); if (fActionSet != null) fActionSet.dispose(); if (fFilterUpdater != null) ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater); super.dispose(); } /** * Implementation of IWorkbenchPart.createPartControl(Composite) */ public void createPartControl(Composite parent) { fViewer= createViewer(parent); fViewer.setUseHashlookup(true); if (!JavaPlugin.USE_WORKING_COPY_OWNERS) { fViewer.setComparer(new PackageExplorerElementComparer()); } initDragAndDrop(); setProviders(); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getTree()); fViewer.getTree().setMenu(fContextMenu); // Register viewer with site. This must be done before making the actions. IWorkbenchPartSite site= getSite(); site.registerContextMenu(menuMgr, fViewer); site.setSelectionProvider(fViewer); site.getPage().addPartListener(fPartListener); if (fMemento != null) { restoreLinkingEnabled(fMemento); } makeActions(); // call before registering for selection changes // Set input after filter and sorter has been set. This avoids resorting and refiltering. restoreFilterAndSorter(); fViewer.setInput(findInputElement()); initFrameActions(); initKeyListener(); fSelectionListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { handleSelectionChanged(event); } }; fViewer.addPostSelectionChangedListener(fSelectionListener); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { fActionSet.handleDoubleClick(event); } }); fViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { fActionSet.handleOpen(event); } }); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); fViewer.addTreeListener(fExpansionListener); if (fMemento != null) restoreUIState(fMemento); fMemento= null; // Set help for the view JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW); fillActionBars(); updateTitle(); fFilterUpdater= new FilterUpdater(fViewer); ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater); } private void initFrameActions() { fActionSet.getUpAction().update(); fActionSet.getBackAction().update(); fActionSet.getForwardAction().update(); } /** * This viewer ensures that non-leaves in the hierarchical * layout are not removed by any filters. * * @since 2.1 */ private ProblemTreeViewer createViewer(Composite composite) { return new ProblemTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) { /* * @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object) */ protected Object[] getFilteredChildren(Object parent) { List list = new ArrayList(); ViewerFilter[] filters = fViewer.getFilters(); Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent); for (int i = 0; i < children.length; i++) { Object object = children[i]; if (!isEssential(object)) { object = filter(object, parent, filters); if (object != null) { list.add(object); } } else list.add(object); } return list.toArray(); } // Sends the object through the given filters private Object filter(Object object, Object parent, ViewerFilter[] filters) { for (int i = 0; i < filters.length; i++) { ViewerFilter filter = filters[i]; if (!filter.select(fViewer, parent, object)) return null; } return object; } /* Checks if a filtered object in essential (ie. is a parent that * should not be removed). */ private boolean isEssential(Object object) { try { if (!isFlatLayout() && object instanceof IPackageFragment) { IPackageFragment fragment = (IPackageFragment) object; return !fragment.isDefaultPackage() && fragment.hasSubpackages(); } } catch (JavaModelException e) { JavaPlugin.log(e); } return false; } protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { IStructuredSelection is= (IStructuredSelection)invalidSelection; List ns= null; if (newSelection instanceof IStructuredSelection) { ns= new ArrayList(((IStructuredSelection)newSelection).toList()); } else { ns= new ArrayList(); } boolean changed= false; for (Iterator iter= is.iterator(); iter.hasNext();) { Object element= iter.next(); if (element instanceof IJavaProject) { IProject project= ((IJavaProject)element).getProject(); if (!project.isOpen()) { ns.add(project); changed= true; } } else if (element instanceof IProject) { IProject project= (IProject)element; if (project.isOpen()) { IJavaProject jProject= JavaCore.create(project); if (jProject != null && jProject.exists()) ns.add(jProject); changed= true; } } } if (changed) { newSelection= new StructuredSelection(ns); setSelection(newSelection); } super.handleInvalidSelection(invalidSelection, newSelection); } }; } /** * Answers whether this part shows the packages flat or hierarchical. * * @since 2.1 */ boolean isFlatLayout() { return fIsCurrentLayoutFlat; } private void setProviders() { //content provider must be set before the label provider fContentProvider= createContentProvider(); fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setContentProvider(fContentProvider); fLabelProvider= createLabelProvider(); fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false)); // problem decoration provided by PackageLabelProvider } void toggleLayout() { // Update current state and inform content and label providers fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat; saveLayoutState(null); fContentProvider.setIsFlatLayout(isFlatLayout()); fLabelProvider.setIsFlatLayout(isFlatLayout()); fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } /** * This method should only be called inside this class * and from test cases. */ public PackageExplorerContentProvider createContentProvider() { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS)); return new PackageExplorerContentProvider(this, showCUChildren, reconcile); } private PackageExplorerLabelProvider createLabelProvider() { return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, fContentProvider); } private void fillActionBars() { IActionBars actionBars= getViewSite().getActionBars(); fActionSet.fillActionBars(actionBars); } private Object findInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IWorkspace) { return JavaCore.create(((IWorkspace)input).getRoot()); } else if (input instanceof IContainer) { IJavaElement element= JavaCore.create((IContainer)input); if (element != null && element.exists()) return element; return input; } //1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective // we can't handle the input // fall back to show the workspace return JavaCore.create(JavaPlugin.getWorkspace().getRoot()); } /** * Answer the property defined by key. */ public Object getAdapter(Class key) { if (key.equals(ISelectionProvider.class)) return fViewer; if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(key); } /** * Returns the tool tip text for the given element. */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { if (element instanceof IJavaModel) result= PackagesMessages.getString("PackageExplorerPart.workspace"); //$NON-NLS-1$ else result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$ } else { result= path.makeRelative().toString(); } } if (fWorkingSetName == null) return result; String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$ if (result.length() == 0) return wsstr; return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$ } public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } /** * @see IWorkbenchPart#setFocus() */ public void setFocus() { fViewer.getTree().setFocus(); } /** * Returns the current selection. */ private ISelection getSelection() { return fViewer.getSelection(); } //---- Action handling ---------------------------------------------------------- /** * Called when the context menu is about to open. Override * to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); fActionSet.setContext(new ActionContext(getSelection())); fActionSet.fillContextMenu(menu); fActionSet.setContext(null); } private void makeActions() { fActionSet= new PackageExplorerActionGroup(this); } //---- Event handling ---------------------------------------------------------- private void initDragAndDrop() { initDrag(); initDrop(); } private void initDrag() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance(), FileTransfer.getInstance()}; TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fViewer), new ResourceTransferDragAdapter(fViewer), new FileTransferDragAdapter(fViewer) }; fViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fViewer, dragListeners)); } private void initDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), FileTransfer.getInstance()}; TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fViewer), new FileTransferDropAdapter(fViewer) }; fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners)); } /** * Handles selection changed in viewer. * Updates global actions. * Links to editor (if option enabled) */ private void handleSelectionChanged(SelectionChangedEvent event) { IStructuredSelection selection= (IStructuredSelection) event.getSelection(); fActionSet.handleSelectionChanged(event); if (isLinkingEnabled()) linkToEditor(selection); } public void selectReveal(ISelection selection) { selectReveal(selection, 0); } private void selectReveal(final ISelection selection, final int count) { Control ctrl= getViewer().getControl(); if (ctrl == null || ctrl.isDisposed()) return; ISelection javaSelection= convertSelection(selection); fViewer.setSelection(javaSelection, true); PackageExplorerContentProvider provider= (PackageExplorerContentProvider)getViewer().getContentProvider(); ISelection cs= fViewer.getSelection(); // If we have Pending changes and the element could not be selected then // we try it again on more time by posting the select and reveal asynchronuoulsy // to the event queue. See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=30700 // for a discussion of the underlying problem. if (count == 0 && provider.hasPendingChanges() && !javaSelection.equals(cs)) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { selectReveal(selection, count + 1); } }); } } private ISelection convertSelection(ISelection s) { if (!(s instanceof IStructuredSelection)) return s; Object[] elements= ((StructuredSelection)s).toArray(); if (!containsResources(elements)) return s; for (int i= 0; i < elements.length; i++) { Object o= elements[i]; if (!(o instanceof IJavaElement)) { if (o instanceof IResource) { IJavaElement jElement= JavaCore.create((IResource)o); if (jElement != null && jElement.exists()) elements[i]= jElement; } else if (o instanceof IAdaptable) { IResource r= (IResource)((IAdaptable)o).getAdapter(IResource.class); if (r != null) { IJavaElement jElement= JavaCore.create(r); if (jElement != null && jElement.exists()) elements[i]= jElement; else elements[i]= r; } } } } return new StructuredSelection(elements); } private boolean containsResources(Object[] elements) { for (int i = 0; i < elements.length; i++) { Object o= elements[i]; if (!(o instanceof IJavaElement)) { if (o instanceof IResource) return true; if ((o instanceof IAdaptable) && ((IAdaptable)o).getAdapter(IResource.class) != null) return true; } } return false; } public void selectAndReveal(Object element) { selectReveal(new StructuredSelection(element)); } boolean isLinkingEnabled() { return fLinkingEnabled; } /** * Initializes the linking enabled setting from the preference store. */ private void initLinkingEnabled() { fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { // ignore selection changes if the package explorer is not the active part. // In this case the selection change isn't triggered by a user. if (!isActivePart()) return; Object obj= selection.getFirstElement(); if (selection.size() == 1) { IEditorPart part= EditorUtility.isOpenInEditor(obj); if (part != null) { IWorkbenchPage page= getSite().getPage(); page.bringToTop(part); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) obj); } } } private boolean isActivePart() { return this == getSite().getPage().getActivePart(); } public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } saveExpansionState(memento); saveSelectionState(memento); saveLayoutState(memento); saveLinkingEnabled(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //saveScrollState(memento, fViewer.getTree()); fActionSet.saveFilterAndSorterState(memento); } private void saveLinkingEnabled(IMemento memento) { memento.putInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, fLinkingEnabled ? 1 : 0); } /** * Saves the current layout state. * * @param memento the memento to save the state into or * <code>null</code> to store the state in the preferences * @since 2.1 */ private void saveLayoutState(IMemento memento) { if (memento != null) { memento.putInteger(TAG_LAYOUT, getLayoutAsInt()); } else { //if memento is null save in preference store IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(TAG_LAYOUT, getLayoutAsInt()); } } private int getLayoutAsInt() { if (fIsCurrentLayoutFlat) return FLAT_LAYOUT; else return HIERARCHICAL_LAYOUT; } protected void saveScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position)); //save horizontal position bar= tree.getHorizontalBar(); position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position)); } protected void saveSelectionState(IMemento memento) { Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray(); if (elements.length > 0) { IMemento selectionMem= memento.createChild(TAG_SELECTION); for (int i= 0; i < elements.length; i++) { IMemento elementMem= selectionMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= elements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier()); } } } protected void saveExpansionState(IMemento memento) { Object expandedElements[]= fViewer.getVisibleExpandedElements(); if (expandedElements.length > 0) { IMemento expandedMem= memento.createChild(TAG_EXPANDED); for (int i= 0; i < expandedElements.length; i++) { IMemento elementMem= expandedMem.createChild(TAG_ELEMENT); // we can only persist JavaElements for now Object o= expandedElements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier()); } } } private void restoreFilterAndSorter() { fViewer.setSorter(new JavaElementSorter()); if (fMemento != null) fActionSet.restoreFilterAndSorterState(fMemento); } private void restoreUIState(IMemento memento) { restoreExpansionState(memento); restoreSelectionState(memento); // commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676 //restoreScrollState(memento, fViewer.getTree()); } private void restoreLinkingEnabled(IMemento memento) { Integer val= memento.getInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR); if (val != null) { fLinkingEnabled= val.intValue() != 0; } } protected void restoreScrollState(IMemento memento, Tree tree) { ScrollBar bar= tree.getVerticalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_VERTICAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore, don't set scrollposition } } bar= tree.getHorizontalBar(); if (bar != null) { try { String posStr= memento.getString(TAG_HORIZONTAL_POSITION); int position; position= new Integer(posStr).intValue(); bar.setSelection(position); } catch (NumberFormatException e) { // ignore don't set scroll position } } } protected void restoreSelectionState(IMemento memento) { IMemento childMem; childMem= memento.getChild(TAG_SELECTION); if (childMem != null) { ArrayList list= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) list.add(element); } fViewer.setSelection(new StructuredSelection(list)); } } protected void restoreExpansionState(IMemento memento) { IMemento childMem= memento.getChild(TAG_EXPANDED); if (childMem != null) { ArrayList elements= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT); for (int i= 0; i < elementMem.length; i++) { Object element= JavaCore.create(elementMem[i].getString(TAG_PATH)); if (element != null) elements.add(element); } fViewer.setExpandedElements(elements.toArray()); } } /** * Create the KeyListener for doing the refresh on the viewer. */ private void initKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { fActionSet.handleKeyEvent(event); } }); } /** * An editor has been activated. Set the selection in this Packages Viewer * to be the editor's input, if linking is enabled. */ void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) return; showInput(getElementOfInput(editor.getEditorInput())); } boolean showInput(Object input) { Object element= null; if (input instanceof IFile && isOnClassPath((IFile)input)) { element= JavaCore.create((IFile)input); } if (element == null) // try a non Java resource element= input; if (element != null) { ISelection newSelection= new StructuredSelection(element); if (!fViewer.getSelection().equals(newSelection)) { try { fViewer.removeSelectionChangedListener(fSelectionListener); fViewer.setSelection(newSelection); while (element != null && fViewer.getSelection().isEmpty()) { // Try to select parent in case element is filtered element= getParent(element); if (element != null) { newSelection= new StructuredSelection(element); fViewer.setSelection(newSelection); } } } finally { fViewer.addSelectionChangedListener(fSelectionListener); } } return true; } return false; } private boolean isOnClassPath(IFile file) { IJavaProject jproject= JavaCore.create(file.getProject()); return jproject.isOnClasspath(file); } /** * Returns the element's parent. * * @return the parent or <code>null</code> if there's no parent */ private Object getParent(Object element) { if (element instanceof IJavaElement) return ((IJavaElement)element).getParent(); else if (element instanceof IResource) return ((IResource)element).getParent(); // else if (element instanceof IStorage) { // can't get parent - see bug 22376 // } return null; } /** * A compilation unit or class was expanded, expand * the main type. */ void expandMainType(Object element) { try { IType type= null; if (element instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit)element; IType[] types= cu.getTypes(); if (types.length > 0) type= types[0]; } else if (element instanceof IClassFile) { IClassFile cf= (IClassFile)element; type= cf.getType(); } if (type != null) { final IType type2= type; Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { Control ctrl2= fViewer.getControl(); if (ctrl2 != null && !ctrl2.isDisposed()) fViewer.expandToLevel(type2, 1); } }); } } } catch(JavaModelException e) { // no reveal } } /** * Returns the element contained in the EditorInput */ Object getElementOfInput(IEditorInput input) { if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); else if (input instanceof IFileEditorInput) return ((IFileEditorInput)input).getFile(); else if (input instanceof JarEntryEditorInput) return ((JarEntryEditorInput)input).getStorage(); return null; } /** * Returns the Viewer. */ TreeViewer getViewer() { return fViewer; } /** * Returns the TreeViewer. */ public TreeViewer getTreeViewer() { return fViewer; } boolean isExpandable(Object element) { if (fViewer == null) return false; return fViewer.isExpandable(element); } void setWorkingSetName(String workingSetName) { fWorkingSetName= workingSetName; } /** * Updates the title text and title tool tip. * Called whenever the input of the viewer changes. */ void updateTitle() { Object input= fViewer.getInput(); String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ if (input == null || (input instanceof IJavaModel)) { setTitle(viewName); setTitleToolTip(""); //$NON-NLS-1$ } else { String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$ setTitle(title); setTitleToolTip(getToolTipText(input)); } } /** * Sets the decorator for the package explorer. * * @param decorator a label decorator or <code>null</code> for no decorations. * @deprecated To be removed */ public void setLabelDecorator(ILabelDecorator decorator) { } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fViewer == null) return; boolean refreshViewer= false; if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) { fActionSet.updateActionBars(getViewSite().getActionBars()); boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); ((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren); refreshViewer= true; } else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { refreshViewer= true; } if (refreshViewer) fViewer.refresh(); } /* (non-Javadoc) * @see IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { if (fViewer != null) { return fViewer.getInput(); } return null; } public void collapseAll() { fViewer.getControl().setRedraw(false); fViewer.collapseToLevel(getViewPartInput(), AbstractTreeViewer.ALL_LEVELS); fViewer.getControl().setRedraw(true); } public PackageExplorerPart() { initLinkingEnabled(); } public boolean show(ShowInContext context) { Object input= context.getInput(); if (input instanceof IEditorInput) { Object elementOfInput= getElementOfInput((IEditorInput)context.getInput()); if (elementOfInput == null) return false; return showInput(elementOfInput); } ISelection selection= context.getSelection(); if (selection != null) { selectReveal(selection); return true; } return false; } /** * Returns the <code>IShowInSource</code> for this view. */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( getViewer().getInput(), getViewer().getSelection()); } }; } /* * @see org.eclipse.ui.views.navigator.IResourceNavigator#setLinkingEnabled(boolean) * @since 2.1 */ public void setLinkingEnabled(boolean enabled) { fLinkingEnabled= enabled; PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, enabled); if (enabled) { IEditorPart editor = getSite().getPage().getActiveEditor(); if (editor != null) { editorActivated(editor); } } } /** * Returns the name for the given element. * Used as the name for the current frame. */ String getFrameName(Object element) { if (element instanceof IJavaElement) { return ((IJavaElement) element).getElementName(); } else { return ((ILabelProvider) getTreeViewer().getLabelProvider()).getText(element); } } void projectStateChanged(Object root) { Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { fViewer.refresh(root, true); // trigger a syntetic selection change so that action refresh their // enable state. fViewer.setSelection(fViewer.getSelection()); } } }
44,862
Bug 44862 Remove task tag quick fix shouldn't automatically delete the full line
In the following code the quick fix to remove the todo deletes the full line rather than just the end of line comment. if (!display.isDisposed()) ;//TODO display.beep(); }
resolved fixed
45d6047
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-15T14:08:07Z
2003-10-14T22:20:00Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/ReorgQuickFixTest.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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.tests.quickfix; import java.util.ArrayList; import java.util.Hashtable; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.jdt.testplugin.JavaProjectHelper; 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.dom.AST; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.ChangeCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.CorrectMainTypeNameProposal; import org.eclipse.jdt.internal.ui.text.correction.CorrectPackageDeclarationProposal; public class ReorgQuickFixTest extends QuickFixTest { private static final Class THIS= ReorgQuickFixTest.class; private IJavaProject fJProject1; private IPackageFragmentRoot fSourceFolder; public ReorgQuickFixTest(String name) { super(name); } public static Test allTests() { return new ProjectTestSetup(new TestSuite(THIS)); } public static Test suite() { if (true) { return allTests(); } else { TestSuite suite= new TestSuite(); suite.addTest(new ReorgQuickFixTest("testMethodWithConstructorName")); return new ProjectTestSetup(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_UNUSED_IMPORT, JavaCore.ERROR); JavaCore.setOptions(options); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); fJProject1= ProjectTestSetup.getProject(); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); } protected void tearDown() throws Exception { JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath()); } public void testUnusedImports() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); Object p1= proposals.get(0); if (!(p1 instanceof CUCorrectionProposal)) { p1= proposals.get(1); } CUCorrectionProposal proposal= (CUCorrectionProposal) p1; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedImportsInDefaultPackage() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("", false, null); StringBuffer buf= new StringBuffer(); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); Object p1= proposals.get(0); if (!(p1 instanceof CUCorrectionProposal)) { p1= proposals.get(1); } CUCorrectionProposal proposal= (CUCorrectionProposal) p1; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedImportOnDemand() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.Vector;\n"); buf.append("import java.net.*;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append(" Vector v;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); Object p1= proposals.get(0); if (!(p1 instanceof CUCorrectionProposal)) { p1= proposals.get(1); } CUCorrectionProposal proposal= (CUCorrectionProposal) p1; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append(" Vector v;\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testCollidingImports() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.security.Permission;\n"); buf.append("import java.security.acl.Permission;\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append(" Permission p;\n"); buf.append(" Vector v;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); Object p1= proposals.get(0); if (!(p1 instanceof CUCorrectionProposal)) { p1= proposals.get(1); } CUCorrectionProposal proposal= (CUCorrectionProposal) p1; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.security.Permission;\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append(" Permission p;\n"); buf.append(" Vector v;\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testWrongPackageStatement() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); boolean hasRename= true, hasMove= true; for (int i= 0; i < proposals.size(); i++) { ChangeCorrectionProposal curr= (ChangeCorrectionProposal) proposals.get(i); if (curr instanceof CorrectPackageDeclarationProposal) { assertTrue("Duplicated proposal", hasRename); hasRename= false; CUCorrectionProposal proposal= (CUCorrectionProposal) curr; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } else { assertTrue("Duplicated proposal", hasMove); hasMove= false; curr.apply(null); IPackageFragment pack2= fSourceFolder.getPackageFragment("test2"); ICompilationUnit cu2= pack2.getCompilationUnit("E.java"); assertTrue("CU does not exist", cu2.exists()); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualStringIgnoreDelim(cu2.getSource(), buf.toString()); } } } public void testWrongPackageStatementFromDefault() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); boolean hasRename= true, hasMove= true; for (int i= 0; i < proposals.size(); i++) { ChangeCorrectionProposal curr= (ChangeCorrectionProposal) proposals.get(i); if (curr instanceof CorrectPackageDeclarationProposal) { assertTrue("Duplicated proposal", hasRename); hasRename= false; CUCorrectionProposal proposal= (CUCorrectionProposal) curr; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } else { assertTrue("Duplicated proposal", hasMove); hasMove= false; curr.apply(null); IPackageFragment pack2= fSourceFolder.getPackageFragment("test2"); ICompilationUnit cu2= pack2.getCompilationUnit("E.java"); assertTrue("CU does not exist", cu2.exists()); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualStringIgnoreDelim(cu2.getSource(), buf.toString()); } } } public void testWrongDefaultPackageStatement() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test2", false, null); StringBuffer buf= new StringBuffer(); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); boolean hasRename= true, hasMove= true; for (int i= 0; i < proposals.size(); i++) { ChangeCorrectionProposal curr= (ChangeCorrectionProposal) proposals.get(i); if (curr instanceof CorrectPackageDeclarationProposal) { assertTrue("Duplicated proposal", hasRename); hasRename= false; CUCorrectionProposal proposal= (CUCorrectionProposal) curr; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } else { assertTrue("Duplicated proposal", hasMove); hasMove= false; curr.apply(null); IPackageFragment pack2= fSourceFolder.getPackageFragment(""); ICompilationUnit cu2= pack2.getCompilationUnit("E.java"); assertTrue("CU does not exist", cu2.exists()); buf= new StringBuffer(); buf.append("public class E {\n"); buf.append("}\n"); assertEqualStringIgnoreDelim(cu2.getSource(), buf.toString()); } } } public void testWrongPackageStatementButColliding() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); buf.append("package test2;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); pack2.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); 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("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testWrongTypeName() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("X.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); boolean hasRename= true, hasMove= true; for (int i= 0; i < proposals.size(); i++) { ChangeCorrectionProposal curr= (ChangeCorrectionProposal) proposals.get(i); if (curr instanceof CorrectMainTypeNameProposal) { assertTrue("Duplicated proposal", hasRename); hasRename= false; CUCorrectionProposal proposal= (CUCorrectionProposal) curr; String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class X {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } else { assertTrue("Duplicated proposal", hasMove); hasMove= false; curr.apply(null); ICompilationUnit cu2= pack1.getCompilationUnit("E.java"); assertTrue("CU does not exist", cu2.exists()); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualStringIgnoreDelim(cu2.getSource(), buf.toString()); } } } public void testWrongTypeNameButColliding() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class X {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class X {\n"); buf.append("}\n"); pack1.createCompilationUnit("X.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); 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("\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testWrongTypeNameWithConstructor() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class X {\n"); buf.append(" public X() {\n"); buf.append(" X other;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class X {\n"); buf.append("}\n"); pack1.createCompilationUnit("X.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); 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("\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" E other;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } }
44,862
Bug 44862 Remove task tag quick fix shouldn't automatically delete the full line
In the following code the quick fix to remove the todo deletes the full line rather than just the end of line comment. if (!display.isDisposed()) ;//TODO display.beep(); }
resolved fixed
45d6047
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-15T14:08:07Z
2003-10-14T22:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TaskMarkerProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; 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.jface.text.Position; import org.eclipse.jdt.internal.corext.dom.TokenScanner; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.textmanipulation.TextRegion; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.ui.text.java.IProblemLocation; /** */ public class TaskMarkerProposal extends CUCorrectionProposal { private IProblemLocation fLocation; public TaskMarkerProposal(ICompilationUnit cu, IProblemLocation location, int relevance) { super("", cu, relevance, null); //$NON-NLS-1$ fLocation= location; setDisplayName(CorrectionMessages.getString("TaskMarkerProposal.description")); //$NON-NLS-1$ setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#createCompilationUnitChange(java.lang.String, org.eclipse.jdt.core.ICompilationUnit, org.eclipse.jdt.internal.corext.textmanipulation.TextEdit) */ protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException { CompilationUnitChange change= super.createCompilationUnitChange(name, cu, rootEdit); Position pos= null; TextBuffer buffer= null; try { buffer= TextBuffer.acquire(change.getFile()); pos= getUpdatedPosition(buffer); } finally { if (buffer != null) { TextBuffer.release(buffer); } } if (pos != null) { rootEdit.addChild(new ReplaceEdit(pos.getOffset(), pos.getLength(), "")); //$NON-NLS-1$ } else { rootEdit.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), "")); //$NON-NLS-1$ } return change; } private Position getUpdatedPosition(TextBuffer buffer) { IScanner scanner= getSurroundingComment(buffer); if (scanner == null) { return null; } int commentStart= scanner.getCurrentTokenStartPosition(); int commentEnd= scanner.getCurrentTokenEndPosition() + 1; TextRegion startRegion= buffer.getLineInformationOfOffset(commentStart); int start= startRegion.getOffset(); if (hasContent(buffer.getContent(start, fLocation.getOffset() - start))) { return null; } int end; if (buffer.getChar(commentStart) == '/' && buffer.getChar(commentStart + 1) == '/') { end= commentEnd; } else { int endLine= buffer.getLineOfOffset(commentEnd - 1); if (endLine + 1 == buffer.getNumberOfLines()) { TextRegion endRegion= buffer.getLineInformation(endLine); end= endRegion.getOffset() + endRegion.getLength(); } else { TextRegion endRegion= buffer.getLineInformation(endLine + 1); end= endRegion.getOffset(); } } int posEnd= fLocation.getOffset() + fLocation.getLength(); if (hasContent(buffer.getContent(posEnd, end - posEnd))) { return null; } return new Position(start, end - start); } private IScanner getSurroundingComment(TextBuffer buffer) { try { IScanner scanner= ToolFactory.createScanner(true, false, false, false); scanner.setSource(buffer.getContent().toCharArray()); scanner.resetTo(0, buffer.getLength() - 1); int start= fLocation.getOffset(); int end= start + fLocation.getLength(); int token= scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (TokenScanner.isComment(token)) { int currStart= scanner.getCurrentTokenStartPosition(); int currEnd= scanner.getCurrentTokenEndPosition() + 1; if (currStart <= start && end <= currEnd) { return scanner; } } token= scanner.getNextToken(); } } catch (InvalidInputException e) { // ignore } return null; } private boolean hasContent(String string) { for (int i= 0; i < string.length(); i++) { char ch= string.charAt(i); if (Character.isLetter(ch)) { return true; } } return false; } }
44,833
Bug 44833 NPE in enable test of MoveStaticMembersRefactoring [refactoring]
!ENTRY org.eclipse.jface 4 2 Okt 14, 2003 18:57:17.787 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersRefactoring.isMoveable(MoveStaticMembersRefactoring.java:234) at org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersRefactoring.areAllMoveable(MoveStaticMembersRefactoring.java:206) at org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersRefactoring.isAvailable(MoveStaticMembersRefactoring.java:195) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveStaticMembersAction.canEnable(MoveStaticMembersAction.java:137) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveStaticMembersAction.selectionChanged(MoveStaticMembersAction.java:68) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged(SelectionDispatchAction.java:184) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.selectionChanged(SelectionDispatchAction.java:179) at org.eclipse.jdt.ui.actions.MoveAction.selectionChanged(MoveAction.java:105) at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:159) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1018) at org.eclipse.core.runtime.Platform.run(Platform.java:461) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java:157) at org.eclipse.jface.viewers.StructuredViewer.updateSelection(StructuredViewer.java:1282) at org.eclipse.jface.viewers.StructuredViewer.setSelection(StructuredViewer.java:1012) at org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart.setSelection(JavaBrowsingPart.java:1160) at org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart.adjustInputAndSetSelection(JavaBrowsingPart.java:967) at org.eclipse.jdt.internal.ui.browsing.JavaBrowsingContentProvider$4.run(JavaBrowsingContentProvider.java:457) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:102) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:2150) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1867) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
verified fixed
fae5285
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-15T15:31:01Z
2003-10-14T16:46:40Z
org.eclipse.jdt.ui/core
44,833
Bug 44833 NPE in enable test of MoveStaticMembersRefactoring [refactoring]
!ENTRY org.eclipse.jface 4 2 Okt 14, 2003 18:57:17.787 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersRefactoring.isMoveable(MoveStaticMembersRefactoring.java:234) at org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersRefactoring.areAllMoveable(MoveStaticMembersRefactoring.java:206) at org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersRefactoring.isAvailable(MoveStaticMembersRefactoring.java:195) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveStaticMembersAction.canEnable(MoveStaticMembersAction.java:137) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveStaticMembersAction.selectionChanged(MoveStaticMembersAction.java:68) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged(SelectionDispatchAction.java:184) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.selectionChanged(SelectionDispatchAction.java:179) at org.eclipse.jdt.ui.actions.MoveAction.selectionChanged(MoveAction.java:105) at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:159) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1018) at org.eclipse.core.runtime.Platform.run(Platform.java:461) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java:157) at org.eclipse.jface.viewers.StructuredViewer.updateSelection(StructuredViewer.java:1282) at org.eclipse.jface.viewers.StructuredViewer.setSelection(StructuredViewer.java:1012) at org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart.setSelection(JavaBrowsingPart.java:1160) at org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart.adjustInputAndSetSelection(JavaBrowsingPart.java:967) at org.eclipse.jdt.internal.ui.browsing.JavaBrowsingContentProvider$4.run(JavaBrowsingContentProvider.java:457) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:102) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:2150) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1867) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
verified fixed
fae5285
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-15T15:31:01Z
2003-10-14T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersRefactoring.java
44,993
Bug 44993 Exception in CodeFormatter with unclosed string litteral
3.0 M4 Save this example class and then choose Source > Format: public class A { String s= "Hello Problem"; } I have not enabled the new code formatter in the prefs. !ENTRY org.eclipse.jdt.ui 4 10001 Oct 16, 2003 08:29:36.509 !MESSAGE Internal Error !STACK 0 org.eclipse.jdt.core.compiler.InvalidInputException: Invalid_Char_In_String at org.eclipse.jdt.internal.core.util.PublicScanner.getNextToken(PublicScanner.java:1134) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.emulateNewWithOld(CodeFormatterUtil.java:289) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:185) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:99) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:86) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:816) at org.eclipse.jface.text.formatter.ContentFormatter.formatMaster(ContentFormatter.java:665) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:489) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:664) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:98) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:169) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:541) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599) !ENTRY org.eclipse.ui 4 4 Oct 16, 2003 08:29:36.530 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Oct 16, 2003 08:29:36.540 !MESSAGE assertion failed; Invalid_Char_In_String !STACK 0 org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; Invalid_Char_In_String at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.emulateNewWithOld(CodeFormatterUtil.java:329) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:185) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:99) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:86) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:816) at org.eclipse.jface.text.formatter.ContentFormatter.formatMaster(ContentFormatter.java:665) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:489) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:664) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:98) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:169) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:541) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
resolved fixed
cea61c6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T09:51:54Z
2003-10-16T07:40:00Z
org.eclipse.jdt.ui/core
44,993
Bug 44993 Exception in CodeFormatter with unclosed string litteral
3.0 M4 Save this example class and then choose Source > Format: public class A { String s= "Hello Problem"; } I have not enabled the new code formatter in the prefs. !ENTRY org.eclipse.jdt.ui 4 10001 Oct 16, 2003 08:29:36.509 !MESSAGE Internal Error !STACK 0 org.eclipse.jdt.core.compiler.InvalidInputException: Invalid_Char_In_String at org.eclipse.jdt.internal.core.util.PublicScanner.getNextToken(PublicScanner.java:1134) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.emulateNewWithOld(CodeFormatterUtil.java:289) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:185) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:99) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:86) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:816) at org.eclipse.jface.text.formatter.ContentFormatter.formatMaster(ContentFormatter.java:665) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:489) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:664) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:98) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:169) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:541) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599) !ENTRY org.eclipse.ui 4 4 Oct 16, 2003 08:29:36.530 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Oct 16, 2003 08:29:36.540 !MESSAGE assertion failed; Invalid_Char_In_String !STACK 0 org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; Invalid_Char_In_String at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.emulateNewWithOld(CodeFormatterUtil.java:329) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:185) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:99) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:86) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:816) at org.eclipse.jface.text.formatter.ContentFormatter.formatMaster(ContentFormatter.java:665) at org.eclipse.jface.text.formatter.ContentFormatter.format(ContentFormatter.java:489) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:664) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:98) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:169) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:541) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
resolved fixed
cea61c6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T09:51:54Z
2003-10-16T07:40:00Z
extension/org/eclipse/jdt/internal/corext/util/CodeFormatterUtil.java
44,936
Bug 44936 Override indicators show only some overrides
Override indicators appear to be broken in 3.0M4. I can (for example) open up one of my classes which extends junit's TestCase, hit Ctrl-O for the fast outline view, or look at the normal outline view, and Eclipse 2.1.1 is shows me 3 overrides (toString(), setUp(), tearDown()), while 3.0M4 shows me only toString() as an override, for some reason. I am unable to put a pattern to this. It just seems to miss some of them...
resolved fixed
30be46f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T10:50:00Z
2003-10-15T20:33:20Z
org.eclipse.jdt.ui/core
44,936
Bug 44936 Override indicators show only some overrides
Override indicators appear to be broken in 3.0M4. I can (for example) open up one of my classes which extends junit's TestCase, hit Ctrl-O for the fast outline view, or look at the normal outline view, and Eclipse 2.1.1 is shows me 3 overrides (toString(), setUp(), tearDown()), while 3.0M4 shows me only toString() as an override, for some reason. I am unable to put a pattern to this. It just seems to miss some of them...
resolved fixed
30be46f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T10:50:00Z
2003-10-15T20:33:20Z
extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java
45,004
Bug 45004 Java Editor Template Insert Variable Broken in 3.0M4
Hi, I've been using the following template for quite a while, and it no longer works in 3.0M4. /** * Commons Logging instance. */ private static final Log LOG = LogFactory.getLog(${enclosing_type}.class); If I use the template now, ${enclosing_type} does not get resolved. I have the same problem with other templates. It seems that none of the "Insert Variable" fields resolve any more. -tim
resolved fixed
fd7f646
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T12:21:18Z
2003-10-16T13:13:20Z
org.eclipse.jdt.ui/core
45,004
Bug 45004 Java Editor Template Insert Variable Broken in 3.0M4
Hi, I've been using the following template for quite a while, and it no longer works in 3.0M4. /** * Commons Logging instance. */ private static final Log LOG = LogFactory.getLog(${enclosing_type}.class); If I use the template now, ${enclosing_type} does not get resolved. I have the same problem with other templates. It seems that none of the "Insert Variable" fields resolve any more. -tim
resolved fixed
fd7f646
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T12:21:18Z
2003-10-16T13:13:20Z
extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitContext.java
44,310
Bug 44310 Escape sequences remain in externalized strings [refactoring] [nls]
I20030930: When using the "Externalize strings" refactoring on a string like: "Ignores all occurrences of \"{0}\" in the document" the escape sequences are not correctly resolved. In the properties file, the newly inserted line looks as follows: key=Ignores all occurrences of \"{0}\" in the document At least escape combinations for " should be correctly translated. Other escape sequences like \r,\n,\b, ... make less sense.
resolved fixed
a0bfeef
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T13:17:31Z
2003-10-07T15:20:00Z
org.eclipse.jdt.ui/core
44,310
Bug 44310 Escape sequences remain in externalized strings [refactoring] [nls]
I20030930: When using the "Externalize strings" refactoring on a string like: "Ignores all occurrences of \"{0}\" in the document" the escape sequences are not correctly resolved. In the properties file, the newly inserted line looks as follows: key=Ignores all occurrences of \"{0}\" in the document At least escape combinations for " should be correctly translated. Other escape sequences like \r,\n,\b, ... make less sense.
resolved fixed
a0bfeef
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T13:17:31Z
2003-10-07T15:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSHolder.java
44,310
Bug 44310 Escape sequences remain in externalized strings [refactoring] [nls]
I20030930: When using the "Externalize strings" refactoring on a string like: "Ignores all occurrences of \"{0}\" in the document" the escape sequences are not correctly resolved. In the properties file, the newly inserted line looks as follows: key=Ignores all occurrences of \"{0}\" in the document At least escape combinations for " should be correctly translated. Other escape sequences like \r,\n,\b, ... make less sense.
resolved fixed
a0bfeef
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T13:17:31Z
2003-10-07T15:20:00Z
org.eclipse.jdt.ui/core
44,310
Bug 44310 Escape sequences remain in externalized strings [refactoring] [nls]
I20030930: When using the "Externalize strings" refactoring on a string like: "Ignores all occurrences of \"{0}\" in the document" the escape sequences are not correctly resolved. In the properties file, the newly inserted line looks as follows: key=Ignores all occurrences of \"{0}\" in the document At least escape combinations for " should be correctly translated. Other escape sequences like \r,\n,\b, ... make less sense.
resolved fixed
a0bfeef
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T13:17:31Z
2003-10-07T15:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSRefactoring.java
44,772
Bug 44772 Java Search opens the wrong file
Build: 3.0M4 1. Navigate > Open type... 2. Enter 'Document' 3. In the list of available choice, click on the interface 'Document'. There are three potential qualifiers: i. javax.swing.text. ii. org.w3c.dom (from the xerces plug-in that I have in my workspace). iii. org.w3c.dom (from rt.jar of my Sun's 1.4.2 JRE) 4. Choose iii. Click OK. You will see that the interface that I chose did not open. Instead the one from ii did.
resolved fixed
1fbbde6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T13:33:03Z
2003-10-13T18:33:20Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/TypeInfoTest.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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.tests.core; import java.io.File; import java.util.ArrayList; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.ITypeNameRequestor; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.util.AllTypesCache; import org.eclipse.jdt.internal.corext.util.IFileTypeInfo; import org.eclipse.jdt.internal.corext.util.JarFileEntryTypeInfo; import org.eclipse.jdt.internal.corext.util.TypeInfo; import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor; public class TypeInfoTest extends TestCase { private static final Class THIS= TypeInfoTest.class; private IJavaProject fJProject1; private IJavaProject fJProject2; public TypeInfoTest(String name) { super(name); } public static Test allTests() { return new ProjectTestSetup(new TestSuite(THIS)); } public static Test suite() { if (true) { return allTests(); } else { TestSuite suite= new TestSuite(); suite.addTest(new TypeInfoTest("test1")); return suite; } } protected void setUp() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); assertNotNull("jre is null", JavaProjectHelper.addRTJar(fJProject1)); fJProject2= JavaProjectHelper.createJavaProject("TestProject2", "bin"); assertNotNull("jre is null", JavaProjectHelper.addRTJar(fJProject2)); // add Junit source to project 2 File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC); assertTrue("Junit source", junitSrcArchive != null && junitSrcArchive.exists()); JavaProjectHelper.addSourceContainerWithImport(fJProject2, "src", junitSrcArchive); } protected void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); JavaProjectHelper.delete(fJProject2); } public void test1() throws Exception { // source folder IPackageFragmentRoot root1= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= root1.createPackageFragment("com.oti", true, null); ICompilationUnit cu1= pack1.getCompilationUnit("V.java"); cu1.createType("public class V {\n static class VInner {\n}\n}\n", null, true, null); // proj1 has proj2 as prerequisit JavaProjectHelper.addRequiredProject(fJProject1, fJProject2); // internal jar //IPackageFragmentRoot root2= JavaProjectHelper.addLibraryWithImport(fJProject1, JARFILE, null, null); ArrayList result= new ArrayList(); IJavaElement[] elements= new IJavaElement[] { fJProject1 }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); ITypeNameRequestor requestor= new TypeInfoRequestor(result); SearchEngine engine= new SearchEngine(); engine.searchAllTypeNames( fJProject1.getJavaModel().getWorkspace(), null, new char[] {'V'}, IJavaSearchConstants.PREFIX_MATCH, IJavaSearchConstants.CASE_INSENSITIVE, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); findTypeRef(result, "com.oti.V"); findTypeRef(result, "com.oti.V.VInner"); findTypeRef(result, "java.lang.VerifyError"); findTypeRef(result, "java.lang.Void"); findTypeRef(result, "java.util.Vector"); findTypeRef(result, "junit.samples.VectorTest"); for (int i= 0; i < result.size(); i++) { TypeInfo ref= (TypeInfo) result.get(i); //System.out.println(ref.getTypeName()); IType resolvedType= ref.resolveType(scope); if (resolvedType == null) { assertTrue("Could not be resolved: " + ref.toString(), false); } } assertTrue("Should find 9 elements, is " + result.size(), result.size() == 9); } private void findTypeRef(List refs, String fullname) { for (int i= 0; i <refs.size(); i++) { TypeInfo curr= (TypeInfo) refs.get(i); if (fullname.equals(curr.getFullyQualifiedName())) { return; } } assertTrue("Type not found: " + fullname, false); } public void test2() throws Exception { ArrayList result= new ArrayList(); IJavaProject[] elements= new IJavaProject[] { fJProject2 }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); ITypeNameRequestor requestor= new TypeInfoRequestor(result); SearchEngine engine= new SearchEngine(); engine.searchAllTypeNames( fJProject1.getJavaModel().getWorkspace(), null, new char[] {'T'}, IJavaSearchConstants.PREFIX_MATCH, IJavaSearchConstants.CASE_INSENSITIVE, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); findTypeRef(result, "junit.extensions.TestDecorator"); findTypeRef(result, "junit.framework.Test"); findTypeRef(result, "junit.framework.TestListener"); findTypeRef(result, "junit.tests.TestCaseTest.TornDown"); assertTrue("Should find 37 elements, is " + result.size(), result.size() == 37); //System.out.println("Elements found: " + result.size()); for (int i= 0; i < result.size(); i++) { TypeInfo ref= (TypeInfo) result.get(i); //System.out.println(ref.getTypeName()); IType resolvedType= ref.resolveType(scope); if (resolvedType == null) { assertTrue("Could not be resolved: " + ref.toString(), false); } } } public void testNoSourceFolder() throws Exception { IPackageFragmentRoot root= JavaProjectHelper.addSourceContainer(fJProject1, ""); IPackageFragment pack1= root.createPackageFragment("", true, null); ICompilationUnit cu1= pack1.getCompilationUnit("A.java"); cu1.createType("public class A {\n}\n", null, true, null); IPackageFragment pack2= root.createPackageFragment("org.eclipse", true, null); ICompilationUnit cu2= pack2.getCompilationUnit("B.java"); cu2.createType("public class B {\n}\n", null, true, null); TypeInfo[] result= AllTypesCache.getAllTypes(new NullProgressMonitor()); for (int i= 0; i < result.length; i++) { TypeInfo info= result[i]; if (info.getElementType() == TypeInfo.IFILE_TYPE_INFO) { IFileTypeInfo fileInfo= (IFileTypeInfo)info; if (info.getTypeName().equals("A")) { assertEquals(info.getPackageName(), ""); assertEquals(fileInfo.getProject(), "TestProject1"); assertNull(fileInfo.getFolder()); assertEquals(fileInfo.getFileName(), "A"); assertEquals(fileInfo.getExtension(), "java"); } else if (info.getTypeName().equals("B")) { assertEquals(info.getPackageName(), "org.eclipse"); assertEquals(fileInfo.getProject(), "TestProject1"); assertNull(fileInfo.getFolder()); assertEquals(fileInfo.getFileName(), "B"); assertEquals(fileInfo.getExtension(), "java"); } } } } public void testSourceFolder() throws Exception { IPackageFragmentRoot root= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= root.createPackageFragment("", true, null); ICompilationUnit cu1= pack1.getCompilationUnit("A.java"); cu1.createType("public class A {\n}\n", null, true, null); IPackageFragment pack2= root.createPackageFragment("org.eclipse", true, null); ICompilationUnit cu2= pack2.getCompilationUnit("B.java"); cu2.createType("public class B {\n}\n", null, true, null); TypeInfo[] result= AllTypesCache.getAllTypes(new NullProgressMonitor()); for (int i= 0; i < result.length; i++) { TypeInfo info= result[i]; if (info.getElementType() == TypeInfo.IFILE_TYPE_INFO) { IFileTypeInfo fileInfo= (IFileTypeInfo)info; if (info.getTypeName().equals("A")) { assertEquals(info.getPackageName(), ""); assertEquals(fileInfo.getProject(), "TestProject1"); assertEquals(fileInfo.getFolder(), "src"); assertEquals(fileInfo.getFileName(), "A"); assertEquals(fileInfo.getExtension(), "java"); } else if (info.getTypeName().equals("B")) { assertEquals(info.getPackageName(), "org.eclipse"); assertEquals(fileInfo.getProject(), "TestProject1"); assertEquals(fileInfo.getFolder(), "src"); assertEquals(fileInfo.getFileName(), "B"); assertEquals(fileInfo.getExtension(), "java"); } } } } public void testJar() throws Exception { TypeInfo[] result= AllTypesCache.getAllTypes(new NullProgressMonitor()); for (int i= 0; i < result.length; i++) { TypeInfo info= result[i]; if (info.getElementType() == TypeInfo.JAR_FILE_ENTRY_TYPE_INFO) { JarFileEntryTypeInfo jarInfo= (JarFileEntryTypeInfo)info; if (info.getTypeName().equals("Object")) { assertEquals(info.getPackageName(), "java.lang"); assertTrue(jarInfo.getJar().endsWith("rtstubs.jar")); assertEquals(jarInfo.getFileName(), "Object"); assertEquals(jarInfo.getExtension(), "class"); } } } } }
44,772
Bug 44772 Java Search opens the wrong file
Build: 3.0M4 1. Navigate > Open type... 2. Enter 'Document' 3. In the list of available choice, click on the interface 'Document'. There are three potential qualifiers: i. javax.swing.text. ii. org.w3c.dom (from the xerces plug-in that I have in my workspace). iii. org.w3c.dom (from rt.jar of my Sun's 1.4.2 JRE) 4. Choose iii. Click OK. You will see that the interface that I chose did not open. Instead the one from ii did.
resolved fixed
1fbbde6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T13:33:03Z
2003-10-13T18:33:20Z
org.eclipse.jdt.ui/core
44,772
Bug 44772 Java Search opens the wrong file
Build: 3.0M4 1. Navigate > Open type... 2. Enter 'Document' 3. In the list of available choice, click on the interface 'Document'. There are three potential qualifiers: i. javax.swing.text. ii. org.w3c.dom (from the xerces plug-in that I have in my workspace). iii. org.w3c.dom (from rt.jar of my Sun's 1.4.2 JRE) 4. Choose iii. Click OK. You will see that the interface that I chose did not open. Instead the one from ii did.
resolved fixed
1fbbde6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-16T13:33:03Z
2003-10-13T18:33:20Z
extension/org/eclipse/jdt/internal/corext/util/JarFileEntryTypeInfo.java
37,249
Bug 37249 Export Javadoc does not give any error when the path to javadoc.exe is bogus
Version: 2.1.0 Build id: 200303272130 I had a bogus path to javadoc.exe in Preferences/Java/Javadoc. When I clicked Finish in the Export/Javadoc wizard, nothing happened. I gave up using the feature until today when I ran accross my bad Preference setting. Obviously, the wizard needed to give the user some kind of error message. (FYI, this happened when I upgraded my set up from Sun's 1.4.1_01 to 1.4.1_02.)
resolved fixed
ca8cce6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T14:05:34Z
2003-05-06T00:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocCommandWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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: * Sebastian Davids <[email protected]> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui.javadocexport; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage; public class JavadocCommandWizardPage extends JavadocWizardPage { private JavadocPreferencePage fPage; protected JavadocCommandWizardPage(String pageName) { super(pageName); setDescription(JavadocExportMessages.getString("JavadocCommandWizardPage.description")); //$NON-NLS-1$ } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); composite.setLayout(new FillLayout()); fPage= new JavadocPreferencePage() { public void createControl(Composite parentComposite) { noDefaultAndApplyButton(); super.createControl(parentComposite); } protected void updateStatus(IStatus status) { if (status.matches(IStatus.INFO)) { status= new StatusInfo(IStatus.ERROR, status.getMessage()); } JavadocCommandWizardPage.this.updateStatus(status); } }; fPage.createControl(composite); setControl(composite); Dialog.applyDialogFont(composite); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JAVADOC_COMMAND_PAGE); } public void init() { updateStatus(new StatusInfo(IStatus.ERROR, "")); //$NON-NLS-1$ } protected void finish() { fPage.performOk(); } }
37,249
Bug 37249 Export Javadoc does not give any error when the path to javadoc.exe is bogus
Version: 2.1.0 Build id: 200303272130 I had a bogus path to javadoc.exe in Preferences/Java/Javadoc. When I clicked Finish in the Export/Javadoc wizard, nothing happened. I gave up using the feature until today when I ran accross my bad Preference setting. Obviously, the wizard needed to give the user some kind of error message. (FYI, this happened when I upgraded my set up from Sun's 1.4.1_01 to 1.4.1_02.)
resolved fixed
ca8cce6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T14:05:34Z
2003-05-06T00:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocTreeWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javadocexport; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; 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.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.ui.help.WorkbenchHelp; 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.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.jarpackager.CheckboxTreeAndListGroup; import org.eclipse.jdt.internal.ui.util.SWTUtil; public class JavadocTreeWizardPage extends JavadocWizardPage { private CheckboxTreeAndListGroup fInputGroup; protected IWorkspaceRoot fRoot; protected String fWorkspace; //private JavadocTreeViewerFilter fFilter; protected Text fDestinationText; protected Text fDocletText; protected Text fDocletTypeText; protected Button fStandardButton; protected Button fDestinationBrowserButton; protected Button fCustomButton; protected Button fPrivateVisibility; protected Button fProtectedVisibility; protected Button fPackageVisibility; protected Button fPublicVisibility; private Label fDocletLabel; private Label fDocletTypeLabel; private Label fDestinationLabel; private CLabel fDescriptionLabel; protected String fVisibilitySelection; protected boolean fDocletSelected; private JavadocOptionsManager fStore; private JavadocWizard fWizard; protected StatusInfo fDestinationStatus; protected StatusInfo fDocletStatus; protected StatusInfo fTreeStatus; protected StatusInfo fPreferenceStatus; protected StatusInfo fWizardStatus; private final int PREFERENCESTATUS= 0; private final int CUSTOMSTATUS= 1; private final int STANDARDSTATUS= 2; private final int TREESTATUS= 3; /** * Constructor for JavadocTreeWizardPage. * @param pageName */ protected JavadocTreeWizardPage(String pageName, JavadocOptionsManager store) { super(pageName); setDescription(JavadocExportMessages.getString("JavadocTreeWizardPage.javadoctreewizardpage.description")); //$NON-NLS-1$ fStore= store; // Status variables fDestinationStatus= new StatusInfo(); fDocletStatus= new StatusInfo(); fTreeStatus= new StatusInfo(); fPreferenceStatus= new StatusInfo(); fWizardStatus= store.getWizardStatus(); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); fWizard= (JavadocWizard) this.getWizard(); Composite composite= new Composite(parent, SWT.NONE); GridLayout compositeGridLayout= new GridLayout(); composite.setLayoutData(createGridData(GridData.FILL_BOTH, 0, 0)); compositeGridLayout.numColumns= 6; composite.setLayout(compositeGridLayout); createInputGroup(composite); createVisibilitySet(composite); createOptionsSet(composite); setControl(composite); Dialog.applyDialogFont(composite); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JAVADOC_TREE_PAGE); } protected void createInputGroup(Composite composite) { createLabel(composite, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.checkboxtreeandlistgroup.label"), createGridData(6)); //$NON-NLS-1$ Composite c= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 1; layout.makeColumnsEqualWidth= true; c.setLayout(layout); c.setLayoutData(createGridData(GridData.FILL_BOTH, 6, 0)); ITreeContentProvider treeContentProvider= new JavadocProjectContentProvider(); ITreeContentProvider listContentProvider= new JavadocMemberContentProvider(); fInputGroup= new CheckboxTreeAndListGroup(c, fStore.getRoot(), treeContentProvider, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), listContentProvider, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), SWT.NONE, convertWidthInCharsToPixels(60), convertHeightInCharsToPixels(10)); fInputGroup.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent e) { doValidation(TREESTATUS); fWizard.removeAllProjects(); setProjects(); } }); //the store will contain at least one project in it's list so long as //the workspace is not empty. if (!fStore.getJavaProjects().isEmpty()) setTreeChecked(fStore.getSelectedElements(), (IJavaProject) fStore.getJavaProjects().get(0)); fInputGroup.aboutToOpen(); } private void createVisibilitySet(Composite composite) { GridLayout visibilityLayout= createGridLayout(4); visibilityLayout.marginHeight= 0; visibilityLayout.marginWidth= 0; Composite visibilityGroup= new Composite(composite, SWT.NONE); visibilityGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 6, 0)); visibilityGroup.setLayout(visibilityLayout); createLabel(visibilityGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.visibilitygroup.label"), createGridData(GridData.FILL_HORIZONTAL, 4, 0)); //$NON-NLS-1$ fPrivateVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.privatebutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$ fPackageVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.packagebutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$ fProtectedVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.protectedbutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$ fPublicVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.publicbutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$ fDescriptionLabel= new CLabel(visibilityGroup, SWT.LEFT); fDescriptionLabel.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 4, convertWidthInCharsToPixels(3) - 3)); // INDENT of CLabel fPrivateVisibility.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (((Button) e.widget).getSelection()) { fVisibilitySelection= fStore.PRIVATE; fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.privatevisibilitydescription.label")); //$NON-NLS-1$ } } }); fPackageVisibility.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (((Button) e.widget).getSelection()) { fVisibilitySelection= fStore.PACKAGE; fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.packagevisibledescription.label")); //$NON-NLS-1$ } } }); fProtectedVisibility.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (((Button) e.widget).getSelection()) { fVisibilitySelection= fStore.PROTECTED; fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.protectedvisibilitydescription.label")); //$NON-NLS-1$ } } }); fPublicVisibility.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (((Button) e.widget).getSelection()) { fVisibilitySelection= fStore.PUBLIC; fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.publicvisibilitydescription.label")); //$NON-NLS-1$ } } }); setVisibilitySettings(); } protected void setVisibilitySettings() { fVisibilitySelection= fStore.getAccess(); fPrivateVisibility.setSelection(fVisibilitySelection.equals(fStore.PRIVATE)); if (fPrivateVisibility.getSelection()) fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.privatevisibilitydescription.label")); //$NON-NLS-1$ //$NON-NLS-1$ fProtectedVisibility.setSelection(fVisibilitySelection.equals(fStore.PROTECTED)); if (fProtectedVisibility.getSelection()) fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.protectedvisibilitydescription.label")); //$NON-NLS-1$ //$NON-NLS-1$ fPackageVisibility.setSelection(fVisibilitySelection.equals(fStore.PACKAGE)); if (fPackageVisibility.getSelection()) fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.packagevisibledescription.label")); //$NON-NLS-1$ //$NON-NLS-1$ fPublicVisibility.setSelection(fVisibilitySelection.equals(fStore.PUBLIC)); if (fPublicVisibility.getSelection()) fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.publicvisibilitydescription.label")); //$NON-NLS-1$ //$NON-NLS-1$ } private void createOptionsSet(Composite composite) { GridLayout optionSetLayout= createGridLayout(3); optionSetLayout.marginHeight= 0; optionSetLayout.marginWidth= 0; Composite optionSetGroup= new Composite(composite, SWT.NONE); optionSetGroup.setLayoutData(createGridData(GridData.FILL_BOTH, 6, 0)); optionSetGroup.setLayout(optionSetLayout); fStandardButton= createButton(optionSetGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.standarddocletbutton.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 3, 0)); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 1; fDestinationLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.destinationfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$ fDestinationText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //there really aught to be a way to specify this ((GridData) fDestinationText.getLayoutData()).widthHint= 200; fDestinationText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(STANDARDSTATUS); } }); fDestinationBrowserButton= createButton(optionSetGroup, SWT.PUSH, JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowse.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, 0)); //$NON-NLS-1$ SWTUtil.setButtonDimensionHint(fDestinationBrowserButton); //Option to use custom doclet fCustomButton= createButton(optionSetGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.customdocletbutton.label"), createGridData(3)); //$NON-NLS-1$ //For Entering location of custom doclet fDocletTypeLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.docletnamefield.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$ fDocletTypeText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 2, 0)); fDocletTypeText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(CUSTOMSTATUS); } }); fDocletLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.docletpathfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$ fDocletText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 2, 0)); fDocletText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(CUSTOMSTATUS); } }); //Add Listeners fCustomButton.addSelectionListener(new EnableSelectionAdapter(new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText }, new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton })); fCustomButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { doValidation(CUSTOMSTATUS); } }); fStandardButton.addSelectionListener(new EnableSelectionAdapter(new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton }, new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText })); fStandardButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { doValidation(STANDARDSTATUS); } }); fDestinationBrowserButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String text= handleFolderBrowseButtonPressed(fDestinationText.getText(), fDestinationText.getShell(), JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowsedialog.title"), //$NON-NLS-1$ JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowsedialog.label")); //$NON-NLS-1$ fDestinationText.setText(text); } }); setOptionSetSettings(); } public boolean getCustom() { return fCustomButton.getSelection(); } private void setOptionSetSettings() { if (!fStore.fromStandard()) { fCustomButton.setSelection(true); fDocletText.setText(fStore.getDocletPath()); fDocletTypeText.setText(fStore.getDocletName()); //take the destination as the destination of the first project fDestinationText.setText(fStore.getDestination((IJavaProject) fWizard.getSelectedProjects().iterator().next())); fDestinationText.setEnabled(false); fDestinationBrowserButton.setEnabled(false); fDestinationLabel.setEnabled(false); } else { fStandardButton.setSelection(true); if (fWizard.getSelectedProjects().size() == 1) fDestinationText.setText(fStore.getDestination((IJavaProject) fWizard.getSelectedProjects().iterator().next())); else fDestinationText.setText(fStore.getDestination()); fDocletText.setText(fStore.getDocletPath()); fDocletTypeText.setText(fStore.getDocletName()); fDocletText.setEnabled(false); fDocletLabel.setEnabled(false); fDocletTypeText.setEnabled(false); fDocletTypeLabel.setEnabled(false); } } /** * Receives of list of elements selected by the user and passes them * to the CheckedTree. List can contain multiple projects and elements from * different projects. If the list of seletected elements is empty a default * project is selected. */ protected void setTreeChecked(IJavaElement[] sourceElements, IJavaProject project) { if (sourceElements.length < 1) fInputGroup.initialCheckTreeItem(project); else { for (int i= 0; i < sourceElements.length; i++) { IJavaElement curr= sourceElements[i]; if (curr instanceof ICompilationUnit) { fInputGroup.initialCheckListItem(curr); } else if (curr instanceof IPackageFragment) { fInputGroup.initialCheckTreeItem(curr); } else if (curr instanceof IJavaProject) { fInputGroup.initialCheckTreeItem(curr); } else if (curr instanceof IPackageFragmentRoot) { IPackageFragmentRoot root= (IPackageFragmentRoot) curr; if (!root.isArchive()) fInputGroup.initialCheckTreeItem(curr); } } } } private IPath[] getSourcePath(IJavaProject[] projects) { ArrayList res= new ArrayList(); //loops through all projects and gets a list if of thier sourpaths for (int k= 0; k < projects.length; k++) { IJavaProject iJavaProject= projects[k]; try { IPackageFragmentRoot[] roots= iJavaProject.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot curr= roots[i]; if (curr.getKind() == IPackageFragmentRoot.K_SOURCE) { IResource resource= curr.getResource(); if (resource != null) { IPath p= resource.getLocation(); if (p != null) { res.add(p); } } } } } catch (JavaModelException e) { JavaPlugin.log(e); } } return (IPath[]) res.toArray(new IPath[res.size()]); } private IPath[] getClassPath(IJavaProject[] javaProjects) { ArrayList res= new ArrayList(); for (int j= 0; j < javaProjects.length; j++) { IJavaProject iJavaProject= javaProjects[j]; try { IPath p= iJavaProject.getProject().getLocation(); if (p == null) continue; IPath outputLocation= p.append(iJavaProject.getOutputLocation()); String[] classPath= JavaRuntime.computeDefaultRuntimeClassPath(iJavaProject); for (int i= 0; i < classPath.length; i++) { String curr= classPath[i]; IPath path= new Path(curr); if (!outputLocation.equals(path)) { res.add(path); } } } catch (CoreException e) { JavaPlugin.log(e); } } return (IPath[]) res.toArray(new IPath[res.size()]); } /** * Gets a list of elements to generated javadoc for from each project. * Javadoc can be generated for either a IPackageFragmentRoot or a ICompilationUnit. */ private IJavaElement[] getSourceElements(IJavaProject[] projects) { ArrayList res= new ArrayList(); try { Set allChecked= fInputGroup.getAllCheckedTreeItems(); Set incompletePackages= new HashSet(); for (int h= 0; h < projects.length; h++) { IJavaProject iJavaProject= projects[h]; IPackageFragmentRoot[] roots= iJavaProject.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot root= roots[i]; if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { IJavaElement[] packs= root.getChildren(); for (int k= 0; k < packs.length; k++) { IJavaElement curr= packs[k]; if (curr.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { // default packages are always incomplete if (curr.getElementName().length() == 0 || !allChecked.contains(curr) || fInputGroup.isTreeItemGreyChecked(curr)) { incompletePackages.add(curr.getElementName()); } } } } } } Iterator checkedElements= fInputGroup.getAllCheckedListItems(); while (checkedElements.hasNext()) { Object element= checkedElements.next(); if (element instanceof ICompilationUnit) { ICompilationUnit unit= (ICompilationUnit) element; if (incompletePackages.contains(unit.getParent().getElementName())) { res.add(unit); } } } Set addedPackages= new HashSet(); checkedElements= allChecked.iterator(); while (checkedElements.hasNext()) { Object element= checkedElements.next(); if (element instanceof IPackageFragment) { IPackageFragment fragment= (IPackageFragment) element; String name= fragment.getElementName(); if (!incompletePackages.contains(name) && !addedPackages.contains(name)) { res.add(fragment); addedPackages.add(name); } } } } catch (JavaModelException e) { JavaPlugin.log(e); } return (IJavaElement[]) res.toArray(new IJavaElement[res.size()]); } protected void finish() { if (fCustomButton.getSelection()) { fStore.setDocletName(fDocletTypeText.getText()); fStore.setDocletPath(fDocletText.getText()); fStore.setFromStandard(false); } if (fStandardButton.getSelection()) { fStore.setFromStandard(true); //in case of a single project selection the personal destination is updated for //storage in the dialog settings if (fWizard.getSelectedProjects().size() == 1) { fStore.setDestination((IJavaProject) fWizard.getSelectedProjects().iterator().next(), fDestinationText.getText()); } //the destination used in javadoc generation fStore.setDestination(fDestinationText.getText()); } IJavaProject[] projects= (IJavaProject[]) fWizard.getSelectedProjects().toArray(new IJavaProject[fWizard.getSelectedProjects().size()]); fStore.setProjects(projects, true); fStore.setSourcepath(getSourcePath(projects)); fStore.setClasspath(getClassPath(projects)); fStore.setAccess(fVisibilitySelection); fStore.setSourceElements(getSourceElements(projects)); } protected void setProjects() { TreeItem[] treeItems= fInputGroup.getTree().getItems(); for (int i= 0; i < treeItems.length; i++) { if (treeItems[i].getChecked()) fWizard.addSelectedProject((IJavaProject) treeItems[i].getData()); } } private void doValidation(int validate) { switch (validate) { case PREFERENCESTATUS : fPreferenceStatus= new StatusInfo(); fDocletStatus= new StatusInfo(); updateStatus(findMostSevereStatus()); break; case CUSTOMSTATUS : if (fCustomButton.getSelection()) { fDestinationStatus= new StatusInfo(); fDocletStatus= new StatusInfo(); String doclet= fDocletTypeText.getText(); String docletPath= fDocletText.getText(); if (doclet.length() == 0) { fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.nodocletname.error")); //$NON-NLS-1$ } else if (JavaConventions.validateJavaTypeName(doclet).matches(IStatus.ERROR)) { fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddocletname.error")); //$NON-NLS-1$ } else if ((docletPath.length() == 0) || !validDocletPath(docletPath)) { fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddocletpath.error")); //$NON-NLS-1$ } updateStatus(findMostSevereStatus()); } break; case STANDARDSTATUS : if (fStandardButton.getSelection()) { fDestinationStatus= new StatusInfo(); fDocletStatus= new StatusInfo(); IPath path= new Path(fDestinationText.getText()); if (Path.ROOT.equals(path) || Path.EMPTY.equals(path)) { fDestinationStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.nodestination.error")); //$NON-NLS-1$ } File file= new File(path.toOSString()); if (!path.isValidPath(path.toOSString()) || file.isFile()) { fDestinationStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddestination.error")); //$NON-NLS-1$ } if ((path.append("package-list").toFile().exists()) || (path.append("index.html").toFile().exists())) //$NON-NLS-1$//$NON-NLS-2$ fDestinationStatus.setWarning(JavadocExportMessages.getString("JavadocTreeWizardPage.warning.mayoverwritefiles")); //$NON-NLS-1$ updateStatus(findMostSevereStatus()); } break; case TREESTATUS : fTreeStatus= new StatusInfo(); if (fInputGroup.getAllCheckedTreeItems().size() == 0) fTreeStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invalidtreeselection.error")); //$NON-NLS-1$ updateStatus(findMostSevereStatus()); break; } //end switch } private boolean validDocletPath(String docletPath) { StringTokenizer tokens= new StringTokenizer(docletPath, ";"); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { File file= new File(tokens.nextToken()); if (!file.exists()) return false; } return true; } /** * Finds the most severe error (if there is one) */ private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fPreferenceStatus, fDestinationStatus, fDocletStatus, fTreeStatus, fWizardStatus }); } public void init() { updateStatus(new StatusInfo()); } public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { doValidation(STANDARDSTATUS); doValidation(CUSTOMSTATUS); doValidation(TREESTATUS); doValidation(PREFERENCESTATUS); } } public IPath getDestination() { if (fStandardButton.getSelection()) { return new Path(fDestinationText.getText()); } return null; } }
37,249
Bug 37249 Export Javadoc does not give any error when the path to javadoc.exe is bogus
Version: 2.1.0 Build id: 200303272130 I had a bogus path to javadoc.exe in Preferences/Java/Javadoc. When I clicked Finish in the Export/Javadoc wizard, nothing happened. I gave up using the feature until today when I ran accross my bad Preference setting. Obviously, the wizard needed to give the user some kind of error message. (FYI, this happened when I upgraded my set up from Sun's 1.4.1_01 to 1.4.1_02.)
resolved fixed
ca8cce6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T14:05:34Z
2003-05-06T00:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWizard.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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 * Sebastian Davids <[email protected]> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui.javadocexport; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventSetListener; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.Launch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceDescription; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.IWizardContainer; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IExportWizard; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbench; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.OpenBrowserUtil; import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog; import org.eclipse.jdt.internal.ui.jarpackager.ConfirmSaveModifiedResourcesDialog; import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; public class JavadocWizard extends Wizard implements IExportWizard { private JavadocCommandWizardPage fJCWPage; private JavadocTreeWizardPage fJTWPage; private JavadocSpecificsWizardPage fJSWPage; private JavadocStandardWizardPage fJSpWPage; private IPath fDestination; private boolean fWriteCustom; private boolean fOpenInBrowser; protected final String CommandDesc= "JavadocCommandPage"; //$NON-NLS-1$ protected final String TreePageDesc= "JavadocTreePage"; //$NON-NLS-1$ protected final String SpecificsPageDesc= "JavadocSpecificsPage"; //$NON-NLS-1$ protected final String StandardPageDesc= "JavadocStandardPage"; //$NON-NLS-1$ private final int YES= 0; private final int YES_TO_ALL= 1; private final int NO= 2; private final int NO_TO_ALL= 3; private final String JAVADOC_ANT_INFORMATION_DIALOG= "javadocAntInformationDialog";//$NON-NLS-1$ private JavadocOptionsManager fStore; private IWorkspaceRoot fRoot; private Set fSelectedProjects; private IFile fXmlJavadocFile; //private ILaunchConfiguration fConfig; public JavadocWizard() { this(null); } public JavadocWizard(IFile xmlJavadocFile) { super(); setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_EXPORT_JAVADOC); setWindowTitle(JavadocExportMessages.getString("JavadocWizard.javadocwizard.title")); //$NON-NLS-1$ setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); fRoot= ResourcesPlugin.getWorkspace().getRoot(); fXmlJavadocFile= xmlJavadocFile; fWriteCustom= false; fSelectedProjects= null; } /* * @see IWizard#performFinish() */ public boolean performFinish() { IJavaProject[] projects= (IJavaProject[]) fSelectedProjects.toArray(new IJavaProject[fSelectedProjects.size()]); //writes the new settings to store if(fJCWPage != null) fJCWPage.finish(); fJTWPage.finish(); if (!fJTWPage.getCustom()) fJSpWPage.finish(); fJSWPage.finish(); // Wizard will not run with unsaved files. if (!checkPreconditions(fStore.getSourceElements())) { return false; } fDestination= new Path(fStore.getDestination()); fDestination.toFile().mkdirs(); this.fOpenInBrowser= fStore.doOpenInBrowser(); //Ask if you wish to set the javadoc location for the projects (all) to //the location of the newly generated javadoc if (fStore.fromStandard()) { try { URL newURL= fDestination.toFile().toURL(); List projs= new ArrayList(); //get javadoc locations for all projects for (int i= 0; i < projects.length; i++) { IJavaProject iJavaProject= projects[i]; URL currURL= JavaUI.getProjectJavadocLocation(iJavaProject); if (!newURL.equals(currURL)) { // currURL can be null //if not all projects have the same javadoc location ask if you want to change //them to have the same javadoc location projs.add(iJavaProject); } } if (!projs.isEmpty()) { setAllJavadocLocations((IJavaProject[]) projs.toArray(new IJavaProject[projs.size()]), newURL); } } catch (MalformedURLException e) { JavaPlugin.log(e); } } if (fJSWPage.generateAnt()) { //@Improve: make a better message OptionalMessageDialog.open(JAVADOC_ANT_INFORMATION_DIALOG, getShell(), JavadocExportMessages.getString("JavadocWizard.antInformationDialog.title"), Window.getDefaultImage(), JavadocExportMessages.getString("JavadocWizard.antInformationDialog.message"), MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); //$NON-NLS-1$ //$NON-NLS-2$ try { fStore.createXML(); } catch (CoreException e) { ExceptionHandler.handle(e, getShell(),JavadocExportMessages.getString("JavadocWizard.error.writeANT.title"), JavadocExportMessages.getString("JavadocWizard.error.writeANT.message")); //$NON-NLS-1$ //$NON-NLS-2$ } } //If the wizard was not launched from an ant file store the setttings if (fXmlJavadocFile == null) { getDialogSettings().addSection(fStore.createDialogSettings()); } if (!executeJavadocGeneration(fStore.createArgumentArray())) return false; return true; } public void setAllJavadocLocations(IJavaProject[] projects, URL newURL) { for (int j= 0; j < projects.length; j++) { IJavaProject iJavaProject= projects[j]; String message= JavadocExportMessages.getFormattedString("JavadocWizard.updatejavadoclocation.message", new String[] { iJavaProject.getElementName(), fDestination.toOSString()}); //$NON-NLS-1$ String[] buttonlabels= new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.NO_TO_ALL_LABEL }; MessageDialog dialog= new MessageDialog(getShell(), JavadocExportMessages.getString("JavadocWizard.updatejavadocdialog.label"), Dialog.getImage(Dialog.DLG_IMG_QUESTION), message, 4, buttonlabels, 1);//$NON-NLS-1$ switch (dialog.open()) { case YES : JavaUI.setProjectJavadocLocation(iJavaProject, newURL); break; case YES_TO_ALL : for (int i= j; i < projects.length; i++) { iJavaProject= projects[i]; JavaUI.setProjectJavadocLocation(iJavaProject, newURL); j++; } break; case NO_TO_ALL : j= projects.length; break; case NO : default : break; } } } private boolean executeJavadocGeneration(String[] args) { Process process= null; try { process= Runtime.getRuntime().exec(args); if (process != null) { // contruct a formatted command line for the process properties StringBuffer buf= new StringBuffer(); for (int i= 0; i < args.length; i++) { buf.append(args[i]); buf.append(' '); } IDebugEventSetListener listener= new JavadocDebugEventListener(); DebugPlugin.getDefault().addDebugEventListener(listener); ILaunchConfigurationWorkingCopy wc= null; try { ILaunchConfigurationType lcType= DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION); String name= JavadocExportMessages.getString("JavadocWizard.launchconfig.name"); //$NON-NLS-1$ wc= lcType.newInstance(null, name); wc.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true); ILaunch newLaunch= new Launch(wc, ILaunchManager.RUN_MODE, null); IProcess iprocess= DebugPlugin.newProcess(newLaunch, process, JavadocExportMessages.getString("JavadocWizard.javadocprocess.label")); //$NON-NLS-1$ iprocess.setAttribute(IProcess.ATTR_CMDLINE, buf.toString()); DebugPlugin.getDefault().getLaunchManager().addLaunch(newLaunch); } catch (CoreException e) { JavaPlugin.log(e); } return true; } } catch (IOException e) { JavaPlugin.log(e); return false; } return false; } /** * Creates a list of all CompilationUnits and extracts from that list a list of dirty * files. The user is then asked to confirm if those resources should be saved or * not. * * @return <code>true</code> if all preconditions are satisfied otherwise false */ private boolean checkPreconditions(IJavaElement[] elements) { ArrayList resources= new ArrayList(); for (int i= 0; i < elements.length; i++) { if (elements[i] instanceof ICompilationUnit) { resources.add(elements[i].getResource()); } } //message could be null IFile[] unSavedFiles= getUnsavedFiles(resources); return saveModifiedResourcesIfUserConfirms(unSavedFiles); } /** * Returns the files which are not saved and which are * part of the files being exported. * * @return an array of unsaved files */ private IFile[] getUnsavedFiles(List resources) { IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors(); Set unsavedFiles= new HashSet(dirtyEditors.length); if (dirtyEditors.length > 0) { for (int i= 0; i < dirtyEditors.length; i++) { if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) { IFile dirtyFile= ((IFileEditorInput) dirtyEditors[i].getEditorInput()).getFile(); if (resources.contains(dirtyFile)) { unsavedFiles.add(dirtyFile); } } } } return (IFile[]) unsavedFiles.toArray(new IFile[unsavedFiles.size()]); } /** * Asks to confirm to save the modified resources * and save them if OK is pressed. Must be run in the display thread. * * @return true if user pressed OK and save was successful. */ private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) { if (confirmSaveModifiedResources(dirtyFiles)) { try { if (saveModifiedResources(dirtyFiles)) return true; } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.message")); //$NON-NLS-1$ //$NON-NLS-2$ } } return false; } /** * Asks the user to confirm to save the modified resources. * * @return true if user pressed OK. */ private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) { if (dirtyFiles == null || dirtyFiles.length == 0) return true; // Get display for further UI operations Display display= getShell().getDisplay(); if (display == null || display.isDisposed()) return false; // Ask user to confirm saving of all files final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(getShell(), dirtyFiles); final int[] intResult= new int[1]; Runnable runnable= new Runnable() { public void run() { intResult[0]= dlg.open(); } }; display.syncExec(runnable); return intResult[0] == IDialogConstants.OK_ID; } /** * Save all of the editors in the workbench. Must be run in the display thread. * * @return true if successful. */ private boolean saveModifiedResources(final IFile[] dirtyFiles) throws CoreException, InvocationTargetException { IWorkspace workspace= ResourcesPlugin.getWorkspace(); IWorkspaceDescription description= workspace.getDescription(); boolean autoBuild= description.isAutoBuilding(); description.setAutoBuilding(false); try { workspace.setDescription(description); // This save operation can not be canceled. try { new ProgressMonitorDialog(getShell()).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles)); } finally { description.setAutoBuilding(autoBuild); workspace.setDescription(description); } } catch (InterruptedException ex) { return false; } return true; } private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) { return new IRunnableWithProgress() { public void run(final IProgressMonitor pm) { IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors(); String name= JavadocExportMessages.getString("JavadocWizard.savetask.name"); //$NON-NLS-1$ pm.beginTask(name, editorsToSave.length); try { List dirtyFilesList= Arrays.asList(dirtyFiles); for (int i= 0; i < editorsToSave.length; i++) { if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) { IFile dirtyFile= ((IFileEditorInput) editorsToSave[i].getEditorInput()).getFile(); if (dirtyFilesList.contains((dirtyFile))) editorsToSave[i].doSave(new SubProgressMonitor(pm, 1)); } pm.worked(1); } } finally { pm.done(); } } }; } /* * @see IWizard#addPages() */ public void addPages() { //bug 38692 if (JavadocPreferencePage.getJavaDocCommand().length() == 0) { fJCWPage= new JavadocCommandWizardPage(CommandDesc); super.addPage(fJCWPage); fJCWPage.init(); } fJTWPage= new JavadocTreeWizardPage(TreePageDesc, fStore); fJSWPage= new JavadocSpecificsWizardPage(SpecificsPageDesc, fStore); fJSpWPage= new JavadocStandardWizardPage(StandardPageDesc, fStore); super.addPage(fJTWPage); super.addPage(fJSpWPage); super.addPage(fJSWPage); fJTWPage.init(); fJSpWPage.init(); fJSWPage.init(); } public void init(IWorkbench workbench, IStructuredSelection structuredSelection) { IDialogSettings settings= getDialogSettings().getSection("javadoc"); //$NON-NLS-1$ fStore= new JavadocOptionsManager(fXmlJavadocFile, settings, structuredSelection); fSelectedProjects= new HashSet(fStore.getJavaProjects()); } private void refresh(IPath path) { if (fRoot.findContainersForLocation(path).length > 0) { try { fRoot.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { JavaPlugin.log(e); } } } private void spawnInBrowser() { if (fOpenInBrowser) { try { IPath indexFile= fDestination.append("index.html"); //$NON-NLS-1$ URL url= indexFile.toFile().toURL(); OpenBrowserUtil.open(url, getShell(), getWindowTitle()); } catch (MalformedURLException e) { JavaPlugin.log(e); } } } private class JavadocDebugEventListener implements IDebugEventSetListener { public void handleDebugEvents(DebugEvent[] events) { for (int i= 0; i < events.length; i++) { if (events[i].getKind() == DebugEvent.TERMINATE) { try { if (!fWriteCustom) { refresh(fDestination); //If destination of javadoc is in workspace then refresh workspace spawnInBrowser(); } } finally { DebugPlugin.getDefault().removeDebugEventListener(this); } return; } } } } public IWizardPage getNextPage(IWizardPage page) { if (page instanceof JavadocTreeWizardPage) { if (!fJTWPage.getCustom()) { return fJSpWPage; } return fJSWPage; } else if (page instanceof JavadocCommandWizardPage) { return fJTWPage; } else if (page instanceof JavadocSpecificsWizardPage) { return null; } else if (page instanceof JavadocStandardWizardPage) return fJSWPage; else return null; } public IWizardPage getPreviousPage(IWizardPage page) { if (page instanceof JavadocSpecificsWizardPage) { if (!fJTWPage.getCustom()) { return fJSpWPage; } return fJSWPage; } else if (page instanceof JavadocCommandWizardPage) { return null; } else if (page instanceof JavadocTreeWizardPage) { return fJCWPage; } else if (page instanceof JavadocStandardWizardPage) return fJTWPage; else return null; } protected void setSelectedProjects(Set projects) { fSelectedProjects= projects; } protected Set getSelectedProjects() { return fSelectedProjects; } protected void addSelectedProject(IJavaProject project) { fSelectedProjects.add(project); } protected void removeSelectedProject(IJavaProject project) { if (fSelectedProjects.contains(project)) fSelectedProjects.remove(project); } void removeAllProjects() { fSelectedProjects.clear(); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#canFinish() */ public boolean canFinish() { //bug 38692 //should not be able to finish wizard by only setting javadoc command IWizardContainer container = getContainer(); if ((container == null) || container.getCurrentPage().equals(fJCWPage)) return false; return super.canFinish(); } }
37,249
Bug 37249 Export Javadoc does not give any error when the path to javadoc.exe is bogus
Version: 2.1.0 Build id: 200303272130 I had a bogus path to javadoc.exe in Preferences/Java/Javadoc. When I clicked Finish in the Export/Javadoc wizard, nothing happened. I gave up using the feature until today when I ran accross my bad Preference setting. Obviously, the wizard needed to give the user some kind of error message. (FYI, this happened when I upgraded my set up from Sun's 1.4.1_01 to 1.4.1_02.)
resolved fixed
ca8cce6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T14:05:34Z
2003-05-06T00:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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 * Sebastian Davids <[email protected]> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.File; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.IVMInstallType; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; public class JavadocPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private StringButtonDialogField fJavadocSelection; private Composite fComposite; private static final String PREF_JAVADOC_COMMAND= PreferenceConstants.JAVADOC_COMMAND; private class JDocDialogFieldAdapter implements IDialogFieldListener, IStringButtonAdapter { /* * @see IDialogFieldListener#dialogFieldChanged(DialogField) */ public void dialogFieldChanged(DialogField field) { doValidation(); } /* * @see IStringButtonAdapter#changeControlPressed(DialogField) */ public void changeControlPressed(DialogField field) { handleFileBrowseButtonPressed(fJavadocSelection.getTextControl(fComposite), null, PreferencesMessages.getString("JavadocPreferencePage.browsedialog.title")); //$NON-NLS-1$ } } /** * Returns the configured Javadoc command or the empty string. */ public static String getJavaDocCommand() { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); String cmd= store.getString(PREF_JAVADOC_COMMAND); if (cmd.length() == 0 && store.getDefaultString(PREF_JAVADOC_COMMAND).length() == 0) { initJavadocCommandDefault(store); cmd= store.getString(PREF_JAVADOC_COMMAND); } return cmd; } public JavadocPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); //setDescription("Javadoc command"); //$NON-NLS-1$ } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVADOC_PREFERENCE_PAGE); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDialogUnits(parent); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 3; fComposite= new Composite(parent, SWT.NONE); fComposite.setLayout(layout); DialogField javaDocCommentLabel= new DialogField(); javaDocCommentLabel.setLabelText(PreferencesMessages.getString("JavadocPreferencePage.description")); //$NON-NLS-1$ javaDocCommentLabel.doFillIntoGrid(fComposite, 3); LayoutUtil.setWidthHint(javaDocCommentLabel.getLabelControl(null), convertWidthInCharsToPixels(80)); JDocDialogFieldAdapter adapter= new JDocDialogFieldAdapter(); fJavadocSelection= new StringButtonDialogField(adapter); fJavadocSelection.setDialogFieldListener(adapter); fJavadocSelection.setLabelText(PreferencesMessages.getString("JavadocPreferencePage.command.label")); //$NON-NLS-1$ fJavadocSelection.setButtonLabel(PreferencesMessages.getString("JavadocPreferencePage.command.button")); //$NON-NLS-1$ fJavadocSelection.doFillIntoGrid(fComposite, 3); LayoutUtil.setHorizontalGrabbing(fJavadocSelection.getTextControl(null)); LayoutUtil.setWidthHint(fJavadocSelection.getTextControl(null), convertWidthInCharsToPixels(10)); initFields(); Dialog.applyDialogFont(fComposite); return fComposite; } /* * @see IWorkbenchPreferencePage#init(IWorkbench) */ public void init(IWorkbench workbench) { } private static void initJavadocCommandDefault(IPreferenceStore store) { File file= findJavaDocCommand(); if (file != null) { store.setDefault(PREF_JAVADOC_COMMAND, file.getPath()); } } private static File findJavaDocCommand() { IVMInstall install= JavaRuntime.getDefaultVMInstall(); if (install != null) { File res= getCommand(install); if (res != null) { return res; } } IVMInstallType[] jreTypes= JavaRuntime.getVMInstallTypes(); for (int i= 0; i < jreTypes.length; i++) { IVMInstallType jreType= jreTypes[i]; IVMInstall[] installs= jreType.getVMInstalls(); for (int k= 0; k < installs.length; k++) { File res= getCommand(installs[i]); if (res != null) { return res; } } } return null; } private static File getCommand(IVMInstall install) { File installLocation= install.getInstallLocation(); if (installLocation != null) { File javaDocCommand= new File(installLocation, "bin/javadoc"); //$NON-NLS-1$ if (javaDocCommand.isFile()) { return javaDocCommand; } javaDocCommand= new File(installLocation, "bin/javadoc.exe"); //$NON-NLS-1$ if (javaDocCommand.isFile()) { return javaDocCommand; } } return null; } private void initFields() { fJavadocSelection.setTextWithoutUpdate(getJavaDocCommand()); } /* (non-Javadoc) * @see org.eclipse.jface.preference.IPreferencePage#performOk() */ public boolean performOk() { getPreferenceStore().setValue(PREF_JAVADOC_COMMAND, fJavadocSelection.getText()); JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store= getPreferenceStore(); initJavadocCommandDefault(store); fJavadocSelection.setText(store.getDefaultString(PREF_JAVADOC_COMMAND)); super.performDefaults(); } private void doValidation() { StatusInfo status= new StatusInfo(); String text= fJavadocSelection.getText(); if (text.length() > 0) { File file= new File(text); if (!file.isFile()) { status.setError(PreferencesMessages.getString("JavadocPreferencePage.error.notexists")); //$NON-NLS-1$ } } else { //bug 38692 status.setInfo(PreferencesMessages.getString("JavadocPreferencePage.info.notset")); //$NON-NLS-1$ } updateStatus(status); } protected void updateStatus(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } protected void handleFileBrowseButtonPressed(Text text, String[] extensions, String title) { FileDialog dialog= new FileDialog(text.getShell()); dialog.setText(title); dialog.setFilterExtensions(extensions); String dirName= text.getText(); if (!dirName.equals("")) { //$NON-NLS-1$ File path= new File(dirName); if (path.exists()) dialog.setFilterPath(dirName); } String selectedDirectory= dialog.open(); if (selectedDirectory != null) text.setText(selectedDirectory); } }
45,124
Bug 45124 [plan item] Place incremental find status into separate status line item
Incremental find uses the workbench window status line. When having a post selection text listener that tries to find and display the error or warning underlying the current selection, the incremental find status and the error message are wipping out each other. Status line contribution item needs no to be editable but should support tooltips. Enable error updating on post selection event in Java editors.
verified fixed
66a6c75
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T14:18:33Z
2003-10-17T17:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import java.util.StringTokenizer; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITextViewerExtension3; import org.eclipse.jface.text.ITextViewerExtension4; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationAccess; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.LineChangeHover; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartService; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.editors.text.DefaultEncodingSupport; import org.eclipse.ui.editors.text.IEncodingSupport; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.AddTaskAction; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.ExtendedTextEditor; import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.ContentOutline; 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.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaChangeHover; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; 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 ExtendedTextEditor implements IViewPartInputProvider { /** * Internal implementation class for a change listener. * @since 3.0 */ protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener { /** * Installs this selection changed listener with the given selection provider. If * the selection provider is a post selection provider, post selection changed * events are the preferred choice, otherwise normal selection changed events * are requested. * * @param selectionProvider */ public void install(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.addPostSelectionChangedListener(this); } else { selectionProvider.addSelectionChangedListener(this); } } /** * Removes this selection changed listener from the given selection provider. * * @param selectionProvider */ public void uninstall(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.removePostSelectionChangedListener(this); } else { selectionProvider.removeSelectionChangedListener(this); } } } /** * Updates the Java outline page selection and this editor's range indicator. * * @since 3.0 */ private class EditorSelectionChangedListener extends AbstractSelectionChangedListener { /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { selectionChanged(); } public void selectionChanged() { ISourceReference element= computeHighlightRangeSourceReference(); synchronizeOutlinePage(element); setSelection(element, false); // updateStatusLine(); } } /** * Updates the selection in the editor's widget with the selection of the outline page. */ class OutlineSelectionChangedListener extends AbstractSelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } } /* * Link mode. */ class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener { /** The session is active. */ private boolean fActive; /** The currently active style range. */ private IRegion fActiveRegion; /** The currently active style range as position. */ private Position fRememberedPosition; /** The hand cursor. */ private Cursor fCursor; /** The link color. */ private Color fColor; /** The key modifier mask. */ private int fKeyModifierMask; public void deactivate() { deactivate(false); } public void deactivate(boolean redrawAll) { if (!fActive) return; repairRepresentation(redrawAll); fActive= false; } public void install() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; updateColor(sourceViewer); sourceViewer.addTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.addDocumentListener(this); text.addKeyListener(this); text.addMouseListener(this); text.addMouseMoveListener(this); text.addFocusListener(this); text.addPaintListener(this); updateKeyModifierMask(); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.addPropertyChangeListener(this); } private void updateKeyModifierMask() { String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER); fKeyModifierMask= computeStateMask(modifiers); if (fKeyModifierMask == -1) { // Fallback to stored state mask fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); } } private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } public void uninstall() { if (fColor != null) { fColor.dispose(); fColor= null; } if (fCursor != null) { fCursor.dispose(); fCursor= null; } ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; sourceViewer.removeTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.removeDocumentListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); if (preferenceStore != null) preferenceStore.removePropertyChangeListener(this); StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; text.removeKeyListener(this); text.removeMouseListener(this); text.removeMouseMoveListener(this); text.removeFocusListener(this); text.removePaintListener(this); } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(JavaEditor.LINK_COLOR)) { ISourceViewer viewer= getSourceViewer(); if (viewer != null) updateColor(viewer); } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) { updateKeyModifierMask(); } } private void updateColor(ISourceViewer viewer) { if (fColor != null) fColor.dispose(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display); } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } private void repairRepresentation() { repairRepresentation(false); } private void repairRepresentation(boolean redrawAll) { if (fActiveRegion == null) return; int offset= fActiveRegion.getOffset(); int length= fActiveRegion.getLength(); fActiveRegion= null; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { resetCursor(viewer); // remove style if (!redrawAll && viewer instanceof ITextViewerExtension2) ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length); else viewer.invalidateTextPresentation(); // remove underline if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; offset= extension.modelOffset2WidgetOffset(offset); } else { offset -= viewer.getVisibleRegion().getOffset(); } StyledText text= viewer.getTextWidget(); try { text.redrawRange(offset, length, true); } catch (IllegalArgumentException x) { JavaPlugin.log(x); } } } // will eventually be replaced by a method provided by jdt.core private IRegion selectWord(IDocument document, int anchor) { try { int offset= anchor; char c; while (offset >= 0) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; --offset; } int start= offset; offset= anchor; int length= document.getLength(); while (offset < length) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; ++offset; } int end= offset; if (start == end) return new Region(start, 0); else return new Region(start + 1, end - start - 1); } catch (BadLocationException x) { return null; } } IRegion getCurrentTextRegion(ISourceViewer viewer) { int offset= getCurrentTextOffset(viewer); if (offset == -1) return null; IJavaElement input= SelectionConverter.getInput(JavaEditor.this); if (input == null) return null; try { IJavaElement[] elements= null; synchronized (input) { elements= ((ICodeAssist) input).codeSelect(offset, 0); } if (elements == null || elements.length == 0) return null; return selectWord(viewer.getDocument(), offset); } catch (JavaModelException e) { return null; } } private int getCurrentTextOffset(ISourceViewer viewer) { try { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return -1; Display display= text.getDisplay(); Point absolutePosition= display.getCursorLocation(); Point relativePosition= text.toControl(absolutePosition); int widgetOffset= text.getOffsetAtLocation(relativePosition); if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; return extension.widgetOffset2ModelOffset(widgetOffset); } else { return widgetOffset + viewer.getVisibleRegion().getOffset(); } } catch (IllegalArgumentException e) { return -1; } } private void highlightRegion(ISourceViewer viewer, IRegion region) { if (region.equals(fActiveRegion)) return; repairRepresentation(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; // highlight region int offset= 0; int length= 0; if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; IRegion widgetRange= extension.modelRange2WidgetRange(region); if (widgetRange == null) return; offset= widgetRange.getOffset(); length= widgetRange.getLength(); } else { offset= region.getOffset() - viewer.getVisibleRegion().getOffset(); length= region.getLength(); } StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset); Color foregroundColor= fColor; Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background; int fontStyle= oldStyleRange== null ? SWT.NORMAL : oldStyleRange.fontStyle; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor, fontStyle); text.setStyleRange(styleRange); // underline text.redrawRange(offset, length, true); fActiveRegion= region; } private void activateCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); if (fCursor == null) fCursor= new Cursor(display, SWT.CURSOR_HAND); text.setCursor(fCursor); } private void resetCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) text.setCursor(null); if (fCursor != null) { fCursor.dispose(); fCursor= null; } } /* * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) */ public void keyPressed(KeyEvent event) { if (fActive) { deactivate(); return; } if (event.keyCode != fKeyModifierMask) { deactivate(); return; } fActive= true; // removed for #25871 // // ISourceViewer viewer= getSourceViewer(); // if (viewer == null) // return; // // IRegion region= getCurrentTextRegion(viewer); // if (region == null) // return; // // highlightRegion(viewer, region); // activateCursor(viewer); } /* * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) */ public void keyReleased(KeyEvent event) { if (!fActive) return; deactivate(); } /* * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) */ public void mouseDoubleClick(MouseEvent e) {} /* * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) */ public void mouseDown(MouseEvent event) { if (!fActive) return; if (event.stateMask != fKeyModifierMask) { deactivate(); return; } if (event.button != 1) { deactivate(); return; } } /* * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) */ public void mouseUp(MouseEvent e) { if (!fActive) return; if (e.button != 1) { deactivate(); return; } boolean wasActive= fCursor != null; deactivate(); if (wasActive) { IAction action= getAction("OpenEditor"); //$NON-NLS-1$ if (action != null) action.run(); } } /* * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) */ public void mouseMove(MouseEvent event) { if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) { deactivate(); return; } if (!fActive) { if (event.stateMask != fKeyModifierMask) return; // modifier was already pressed fActive= true; } ISourceViewer viewer= getSourceViewer(); if (viewer == null) { deactivate(); return; } StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) { deactivate(); return; } if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) { deactivate(); return; } IRegion region= getCurrentTextRegion(viewer); if (region == null || region.getLength() == 0) { repairRepresentation(); return; } highlightRegion(viewer, region); activateCursor(viewer); } /* * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) */ public void focusGained(FocusEvent e) {} /* * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent event) { deactivate(); } /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { if (fActive && fActiveRegion != null) { fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength()); try { event.getDocument().addPosition(fRememberedPosition); } catch (BadLocationException x) { fRememberedPosition= null; } } } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { if (fRememberedPosition != null) { if (!fRememberedPosition.isDeleted()) { event.getDocument().removePosition(fRememberedPosition); fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength()); fRememberedPosition= null; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { StyledText widget= viewer.getTextWidget(); if (widget != null && !widget.isDisposed()) { widget.getDisplay().asyncExec(new Runnable() { public void run() { deactivate(); } }); } } } else { fActiveRegion= null; fRememberedPosition= null; deactivate(); } } } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput == null) return; deactivate(); oldInput.removeDocumentListener(this); } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput == null) return; newInput.addDocumentListener(this); } /* * @see PaintListener#paintControl(PaintEvent) */ public void paintControl(PaintEvent event) { if (fActiveRegion == null) return; ISourceViewer viewer= getSourceViewer(); if (viewer == null) return; StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; int offset= 0; int length= 0; if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length)); if (widgetRange == null) return; offset= widgetRange.getOffset(); length= widgetRange.getLength(); } else { IRegion region= viewer.getVisibleRegion(); if (!includes(region, fActiveRegion)) return; offset= fActiveRegion.getOffset() - region.getOffset(); length= fActiveRegion.getLength(); } // support for bidi Point minLocation= getMinimumLocation(text, offset, length); Point maxLocation= getMaximumLocation(text, offset, length); int x1= minLocation.x; int x2= minLocation.x + maxLocation.x - minLocation.x - 1; int y= minLocation.y + text.getLineHeight() - 1; GC gc= event.gc; if (fColor != null && !fColor.isDisposed()) gc.setForeground(fColor); gc.drawLine(x1, y, x2, y); } private boolean includes(IRegion region, IRegion position) { return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); } private Point getMinimumLocation(StyledText text, int offset, int length) { Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x < minLocation.x) minLocation.x= location.x; if (location.y < minLocation.y) minLocation.y= location.y; } return minLocation; } private Point getMaximumLocation(StyledText text, int offset, int length) { Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x > maxLocation.x) maxLocation.x= location.x; if (location.y > maxLocation.y) maxLocation.y= location.y; } return maxLocation; } } /** * This action dispatches into two behaviours: If there is no current text * hover, the javadoc is displayed using information presenter. If there is * a current text hover, it is converted into a information presenter in * order to make it sticky. */ class InformationDispatchAction extends TextEditorAction { /** The wrapped text operation action. */ private final TextOperationAction fTextOperationAction; /** * Creates a dispatch action. */ public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) { super(resourceBundle, prefix, JavaEditor.this); if (textOperationAction == null) throw new IllegalArgumentException(); fTextOperationAction= textOperationAction; } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { /** * Information provider used to present the information. * * @since 3.0 */ class InformationProvider implements IInformationProvider, IInformationProviderExtension2 { private IRegion fHoverRegion; private String fHoverInfo; private IInformationControlCreator fControlCreator; InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) { fHoverRegion= hoverRegion; fHoverInfo= hoverInfo; fControlCreator= controlCreator; } /* * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int) */ public IRegion getSubject(ITextViewer textViewer, int invocationOffset) { return fHoverRegion; } /* * @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 fHoverInfo; } /* * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator() * @since 3.0 */ public IInformationControlCreator getInformationPresenterControlCreator() { return fControlCreator; } } ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) { fTextOperationAction.run(); return; } if (sourceViewer instanceof ITextViewerExtension4) { ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer; if (extension4.moveFocusToWidgetToken()) 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 String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset); IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset); if (hoverRegion == null) return; String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion); IInformationControlCreator controlCreator= null; if (textHover instanceof IInformationProviderExtension2) controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator(); IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator); fInformationPresenter.setOffset(offset); fInformationPresenter.setInformationProvider(informationProvider, contentType); fInformationPresenter.showInformation(); } catch (BadLocationException e) { } } // modified version from TextViewer private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { StyledText styledText= textViewer.getTextWidget(); IDocument document= textViewer.getDocument(); if (document == null) return -1; try { int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y)); if (textViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer; return extension.widgetOffset2ModelOffset(widgetLocation); } else { IRegion visibleRegion= textViewer.getVisibleRegion(); return widgetLocation + visibleRegion.getOffset(); } } catch (IllegalArgumentException e) { return -1; } } } static protected class AnnotationAccess extends DefaultMarkerAnnotationAccess { public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) { super(markerAnnotationPreferences); } /* * @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation) */ public Object getType(Annotation annotation) { if (annotation instanceof IJavaAnnotation) { IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation; if (javaAnnotation.isRelevant()) return javaAnnotation.getAnnotationType(); return null; } return super.getType(annotation); } /* * @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation) */ public boolean isMultiLine(Annotation annotation) { return true; } /* * @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation) */ public boolean isTemporary(Annotation annotation) { if (annotation instanceof IJavaAnnotation) { IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation; if (javaAnnotation.isRelevant()) return javaAnnotation.isTemporary(); } return false; } } private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { handlePreferencePropertyChanged(event); } } /** * This action implements smart home. * * Instead of going to the start of a line it does the following: * * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account. * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line see first case. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); getTextWidget().showSelection(); fireSelectionChanged(); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); final int caret= text.getCaretOffset(); final int offset= modelOffset2WidgetOffset(viewer, position); if (caret == selection.x) text.setSelectionRange(selection.y, offset - selection.y); else text.setSelectionRange(selection.x, offset - selection.x); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); while (position >= 0 && Character.isUpperCase(character)) character= document.getChar(--position); setCaretPosition(position + 1); getTextWidget().showSelection(); fireSelectionChanged(); return; } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); final int caret= text.getCaretOffset(); final int offset= modelOffset2WidgetOffset(viewer, position); if (caret == selection.x) text.setSelectionRange(selection.y, offset - selection.y); else text.setSelectionRange(selection.x, offset - selection.x); } } } /** * Quick format action to format the enclosing java element. * <p> * The quick format action works as follows: * <ul> * <li>If there is no selection and the caret is positioned on a Java element, * only this element is formatted. If the element has some accompanying comment, * then the comment is formatted as well.</li> * <li>If the selection spans one or more partitions of the document, then all * partitions covered by the selection are entirely formatted.</li> * <p> * Partitions at the end of the selection are not completed, except for comments. * * @since 3.0 */ protected class QuickFormatAction extends Action { /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer(); if (viewer.isEditable()) { final Point selection= viewer.rememberSelection(); try { viewer.setRedraw(false); final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x); if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) { try { final IJavaElement element= getElementAt(selection.x, true); if (element != null && element.exists()) { final int kind= element.getElementType(); if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) { final ISourceReference reference= (ISourceReference)element; final ISourceRange range= reference.getSourceRange(); if (range != null) { viewer.setSelectedRange(range.getOffset(), range.getLength()); viewer.doOperation(ISourceViewer.FORMAT); } } } } catch (JavaModelException exception) { // Should not happen } } else { viewer.setSelectedRange(selection.x, 1); viewer.doOperation(ISourceViewer.FORMAT); } } catch (BadLocationException exception) { // Can not happen } finally { viewer.setRedraw(true); viewer.restoreSelection(); } } } } /** Preference key for the link color */ protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR; /** Preference key for matching brackets */ protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS; /** Preference key for matching brackets color */ protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; /** Preference key for compiler task tags */ private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; /** Preference key for browser like links */ private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS; /** Preference key for key modifier of browser like links */ private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER; /** * Preference key for key modifier mask of browser like links. * The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code> * cannot be resolved to valid SWT modifier bits. * * @since 2.1.1 */ private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK; protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' }; /** The outline page */ protected JavaOutlinePage fOutlinePage; /** Outliner context menu Id */ protected String fOutlinerContextMenuId; /** * The editor selection changed listener. * * @since 3.0 */ private EditorSelectionChangedListener fEditorSelectionChangedListener; /** The selection changed listener */ protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener(); /** The editor's bracket matcher */ protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS); /** This editor's encoding support */ private DefaultEncodingSupport fEncodingSupport; /** The mouse listener */ private MouseClickListener fMouseListener; /** The information presenter. */ private InformationPresenter fInformationPresenter; /** History for structure select action */ private SelectionHistory fSelectionHistory; /** The preference property change listener for java core. */ private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener(); /** * Indicates whether this editor is about to update any annotation views. * @since 3.0 */ private boolean fIsUpdatingAnnotationViews= false; /** * The marker that served as last target for a goto marker request. * @since 3.0 */ private IMarker fLastMarkerTarget= null; 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 * @return the most narrow java 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, IJavaPartitions.JAVA_PARTITIONING)); setRangeIndicator(new DefaultRangeIndicator()); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$ } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) { ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles); StyledText text= viewer.getTextWidget(); text.addBidiSegmentListener(new BidiSegmentListener() { public void lineGetSegments(BidiSegmentEvent event) { event.segments= getBidiLineSegments(event.lineOffset, event.lineText); } }); JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); // ensure source viewer decoration support has been created and configured getSourceViewerDecorationSupport(viewer); return viewer; } /* * @see org.eclipse.ui.texteditor.ExtendedTextEditor#createAnnotationAccess() */ protected IAnnotationAccess createAnnotationAccess() { return new AnnotationAccess(new MarkerAnnotationPreferences()); } public final ISourceViewer getViewer() { return getSourceViewer(); } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) { return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles); } /* * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.affectsBehavior(event); } /** * Sets the outliner's context menu ID. */ protected void setOutlinerContextMenuId(String menuId) { fOutlinerContextMenuId= menuId; } /** * Returns the standard action group of this editor. */ protected ActionGroup getActionGroup() { return fActionGroups; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN)); menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW)); ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /** * Creates the outline page used with this editor. */ protected JavaOutlinePage createOutlinePage() { JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this); fOutlineSelectionChangedListener.install(page); setOutlinePageInput(page, getEditorInput()); return page; } /** * Informs the editor that its outliner has been closed. */ public void outlinePageClosed() { if (fOutlinePage != null) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage= null; resetHighlightRange(); } } /** * Synchronizes the outliner selection with the given element * position in the editor. * * @param element the java element to select */ protected void synchronizeOutlinePage(ISourceReference element) { synchronizeOutlinePage(element, true); } /** * Synchronizes the outliner selection with the given element * position in the editor. * * @param element the java element to select * @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done */ protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) { if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select(element); fOutlineSelectionChangedListener.install(fOutlinePage); } } /** * Synchronizes the outliner selection with the actual cursor * position in the editor. */ public void synchronizeOutlinePageSelection() { synchronizeOutlinePage(computeHighlightRangeSourceReference()); } /* * Get the desktop's StatusLineManager */ protected IStatusLineManager getStatusLineManager() { IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) { return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); } return null; } /* * @see AbstractTextEditor#getAdapter(Class) */ public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { if (fOutlinePage == null) fOutlinePage= createOutlinePage(); return fOutlinePage; } if (IEncodingSupport.class.equals(required)) return fEncodingSupport; if (required == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(required); } protected void setSelection(ISourceReference reference, boolean moveCursor) { ISelection selection= getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection= (TextSelection) selection; // PR 39995: [navigation] Forward history cleared after going back in navigation history: // mark only in navigation history if the cursor is being moved (which it isn't if // this is called from a PostSelectionEvent that should only update the magnet) if (moveCursor && (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; setHighlightRange(offset, length, moveCursor); if (!moveCursor) return; offset= -1; length= -1; if (reference instanceof IMember) { range= ((IMember) reference).getNameRange(); if (range != null) { offset= range.getOffset(); length= range.getLength(); } } else if (reference instanceof IImportDeclaration) { String name= ((IImportDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); if (content != null) { offset= range.getOffset() + content.indexOf(name); length= name.length(); } } } else if (reference instanceof IPackageDeclaration) { String name= ((IPackageDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); if (content != null) { offset= range.getOffset() + content.indexOf(name); length= name.length(); } } } if (offset > -1 && length > 0) { try { textWidget.setRedraw(false); sourceViewer.revealRange(offset, length); sourceViewer.setSelectedRange(offset, length); } finally { textWidget.setRedraw(true); } markInNavigationHistory(); } } catch (JavaModelException x) { } catch (IllegalArgumentException x) { } } 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) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select(reference); fOutlineSelectionChangedListener.install(fOutlinePage); } } } 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); setSelection(reference, !isActivePart()); } /* * @see AbstractTextEditor#adjustHighlightRange(int, int) */ protected void adjustHighlightRange(int offset, int length) { try { IJavaElement element= getElementAt(offset); while (element instanceof ISourceReference) { ISourceRange range= ((ISourceReference) element).getSourceRange(); if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) { setHighlightRange(range.getOffset(), range.getLength(), true); if (fOutlinePage != null) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select((ISourceReference) element); fOutlineSelectionChangedListener.install(fOutlinePage); } return; } element= element.getParent(); } } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); } resetHighlightRange(); } protected boolean isActivePart() { IWorkbenchPart part= getActivePart(); return part != null && part.equals(this); } private boolean isJavaOutlinePageActive() { IWorkbenchPart part= getActivePart(); return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage; } private IWorkbenchPart getActivePart() { IWorkbenchWindow window= getSite().getWorkbenchWindow(); IPartService service= window.getPartService(); IWorkbenchPart part= service.getActivePart(); return part; } /* * @see StatusTextEditor#getStatusHeader(IStatus) */ protected String getStatusHeader(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusHeader(status); if (message != null) return message; } return super.getStatusHeader(status); } /* * @see StatusTextEditor#getStatusBanner(IStatus) */ protected String getStatusBanner(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusBanner(status); if (message != null) return message; } return super.getStatusBanner(status); } /* * @see StatusTextEditor#getStatusMessage(IStatus) */ protected String getStatusMessage(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusMessage(status); if (message != null) return message; } return super.getStatusMessage(status); } /* * @see AbstractTextEditor#doSetInput */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (fEncodingSupport != null) fEncodingSupport.reset(); setOutlinePageInput(fOutlinePage, input); } /* * @see IWorkbenchPart#dispose() */ public void dispose() { if (isBrowserLikeLinks()) disableBrowserLikeLinks(); if (fEncodingSupport != null) { fEncodingSupport.dispose(); fEncodingSupport= null; } if (fPropertyChangeListener != null) { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fBracketMatcher != null) { fBracketMatcher.dispose(); fBracketMatcher= null; } if (fSelectionHistory != null) { fSelectionHistory.dispose(); fSelectionHistory= null; } if (fEditorSelectionChangedListener != null) { fEditorSelectionChangedListener.uninstall(getSelectionProvider()); fEditorSelectionChangedListener= null; } super.dispose(); } protected void createActions() { super.createActions(); ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$ resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION); resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK); setAction(ITextEditorActionConstants.ADD_TASK, resAction); ActionGroup oeg, ovg, jsg, sg; fActionGroups= new CompositeActionGroup(new ActionGroup[] { oeg= new OpenEditorActionGroup(this), sg= new ShowActionGroup(this), ovg= new OpenViewActionGroup(this), jsg= new JavaSearchActionGroup(this) }); fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg}); resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$ resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC); setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION); Action action= new GotoMatchingBracketAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE); setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE); setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY); setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); fEncodingSupport= new DefaultEncodingSupport(); fEncodingSupport.initialize(this); fSelectionHistory= new SelectionHistory(this); action= new StructureSelectEnclosingAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING); setAction(StructureSelectionAction.ENCLOSING, action); action= new StructureSelectNextAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT); setAction(StructureSelectionAction.NEXT, action); action= new StructureSelectPreviousAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS); setAction(StructureSelectionAction.PREVIOUS, action); StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory); historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST); setAction(StructureSelectionAction.HISTORY, historyAction); fSelectionHistory.setHistoryAction(historyAction); action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER); setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); action= new QuickFormatAction(); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT); setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action); } 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 (isJavaEditorHoverProperty(property)) updateHoverBehavior(); if (BROWSER_LIKE_LINKS.equals(property)) { if (isBrowserLikeLinks()) enableBrowserLikeLinks(); else disableBrowserLikeLinks(); return; } if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) { if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) { fEditorSelectionChangedListener= new EditorSelectionChangedListener(); fEditorSelectionChangedListener.install(getSelectionProvider()); fEditorSelectionChangedListener.selectionChanged(); } else { fEditorSelectionChangedListener.uninstall(getSelectionProvider()); fEditorSelectionChangedListener= null; } return; } if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) { if (event.getNewValue() instanceof Boolean) { Boolean disable= (Boolean) event.getNewValue(); configureInsertMode(OVERWRITE, !disable.booleanValue()); } } } finally { super.handlePreferenceStoreChanged(event); } } /** * Initializes the given viewer's colors. * * @param viewer the viewer to be initialized * @since 3.0 */ protected void initializeViewerColors(ISourceViewer viewer) { // is handled by JavaSourceViewer } private boolean isJavaEditorHoverProperty(String property) { return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property); } /** * Return whether the browser like links should be enabled * according to the preference store settings. * @return <code>true</code> if the browser like links should be enabled */ private boolean isBrowserLikeLinks() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(BROWSER_LIKE_LINKS); } /** * Enables browser like links. */ private void enableBrowserLikeLinks() { if (fMouseListener == null) { fMouseListener= new MouseClickListener(); fMouseListener.install(); } } /** * Disables browser like links. */ private void disableBrowserLikeLinks() { if (fMouseListener != null) { fMouseListener.uninstall(); fMouseListener= null; } } /** * Handles a property change event describing a change * of the java core's preferences and updates the preference * related editor properties. * * @param event the property change event */ protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { if (COMPILER_TASK_TAGS.equals(event.getProperty())) { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue()))) sourceViewer.invalidateTextPresentation(); } } /** * Returns a segmentation of the line of the given viewer's input document appropriate for * bidi rendering. The default implementation returns only the string literals of a java code * line as segments. * * @param viewer the text viewer * @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(ITextViewer viewer, int lineOffset) throws BadLocationException { IDocument document= viewer.getDocument(); if (document == null) return null; IRegion line= document.getLineInformationOfOffset(lineOffset); ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength()); List segmentation= new ArrayList(); for (int i= 0; i < linePartitioning.length; i++) { if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType())) segmentation.add(linePartitioning[i]); } if (segmentation.size() == 0) return null; int size= segmentation.size(); int[] segments= new int[size * 2 + 1]; int j= 0; for (int i= 0; i < size; i++) { ITypedRegion segment= (ITypedRegion) segmentation.get(i); if (i == 0) segments[j++]= 0; int offset= segment.getOffset() - lineOffset; if (offset > segments[j - 1]) segments[j++]= offset; if (offset + segment.getLength() >= line.getLength()) break; segments[j++]= offset + segment.getLength(); } if (j < segments.length) { int[] result= new int[j]; System.arraycopy(segments, 0, result, 0, j); segments= result; } return segments; } /** * Returns a segmentation of the given line appropriate for bidi rendering. The default * implementation returns only the string literals of a java code line as segments. * * @param lineOffset the offset of the line * @param line the content of the line * @return the line's bidi segmentation */ protected int[] getBidiLineSegments(int widgetLineOffset, String line) { if (line != null && line.length() > 0) { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer != null) { int lineOffset; if (sourceViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer; lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset); } else { IRegion visible= sourceViewer.getVisibleRegion(); lineOffset= visible.getOffset() + widgetLineOffset; } try { return getBidiLineSegments(sourceViewer, lineOffset); } catch (BadLocationException x) { // don't segment line in this case } } } return null; } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() */ protected void updatePropertyDependentActions() { super.updatePropertyDependentActions(); if (fEncodingSupport != null) fEncodingSupport.reset(); } /* * Update the hovering behavior depending on the preferences. */ private void updateHoverBehavior() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(getSourceViewer()); for (int i= 0; i < types.length; i++) { String t= types[i]; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension2) { // Remove existing hovers ((ITextViewerExtension2)sourceViewer).removeTextHovers(t); int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); if (stateMasks != null) { for (int j= 0; j < stateMasks.length; j++) { int stateMask= stateMasks[j]; ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover= configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } /* * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return getEditorInput().getAdapter(IJavaElement.class); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) */ protected void doSetSelection(ISelection selection) { super.doSetSelection(selection); synchronizeOutlinePageSelection(); } /* * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(fPropertyChangeListener); IInformationControlCreator informationControlCreator= new IInformationControlCreator() { public IInformationControl createInformationControl(Shell shell) { boolean cutDown= false; int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown)); } }; fInformationPresenter= new InformationPresenter(informationControlCreator); fInformationPresenter.setSizeConstraints(60, 10, true, true); fInformationPresenter.install(getSourceViewer()); if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) { fEditorSelectionChangedListener= new EditorSelectionChangedListener(); fEditorSelectionChangedListener.install(getSelectionProvider()); } if (isBrowserLikeLinks()) enableBrowserLikeLinks(); if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)) configureInsertMode(OVERWRITE, false); } protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { support.setCharacterPairMatcher(fBracketMatcher); support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR); super.configureSourceViewerDecorationSupport(support); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker) */ public void gotoMarker(IMarker marker) { fLastMarkerTarget= marker; if (!fIsUpdatingAnnotationViews) super.gotoMarker(marker); } /** * Jumps to the next enabled annotation according to the given direction. * An annotation type is enabled if it is configured to be in the * Next/Previous tool bar drop down menu and if it is checked. * * @param forward <code>true</code> if search direction is forward, <code>false</code> if backward */ public void gotoAnnotation(boolean forward) { ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection(); Position position= new Position(0, 0); if (false /* delayed */) { getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); selectAndReveal(position.getOffset(), position.getLength()); } else /* no delay */ { Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); setStatusLineErrorMessage(null); if (annotation != null) { updateAnnotationViews(annotation); selectAndReveal(position.getOffset(), position.getLength()); if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation)annotation).isProblem()) setStatusLineErrorMessage(((IJavaAnnotation)annotation).getMessage()); } } } /** * Updates the annotation views that show the given annotation. * * @param annotation the annotation */ private void updateAnnotationViews(Annotation annotation) { IMarker marker= null; if (annotation instanceof MarkerAnnotation) marker= ((MarkerAnnotation) annotation).getMarker(); else if (annotation instanceof IJavaAnnotation) { Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator(); if (e != null) { while (e.hasNext()) { Object o= e.next(); if (o instanceof MarkerAnnotation) { marker= ((MarkerAnnotation) o).getMarker(); break; } } } } if (marker != null && !marker.equals(fLastMarkerTarget)) { try { boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM); IWorkbenchPage page= getSite().getPage(); IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$ if (view != null) { Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$ method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE }); } } catch (CoreException x) { } catch (NoSuchMethodException x) { } catch (IllegalAccessException x) { } catch (InvocationTargetException x) { } // ignore exceptions, don't update any of the lists, just set statusline } } protected void updateStatusLine() { ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection(); Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength()); setStatusLineErrorMessage(null); if (annotation != null) { try { fIsUpdatingAnnotationViews= true; updateAnnotationViews(annotation); } finally { fIsUpdatingAnnotationViews= false; } if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation)annotation).isProblem()) setStatusLineErrorMessage(((IJavaAnnotation)annotation).getMessage()); } } /** * Jumps to the matching bracket. */ public void gotoMatchingBracket() { ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); if (document == null) return; IRegion selection= getSignedSelection(sourceViewer); int selectionLength= Math.abs(selection.getLength()); if (selectionLength > 1) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } // #26314 int sourceCaretOffset= selection.getOffset() + selection.getLength(); if (isSurroundedByBrackets(document, sourceCaretOffset)) sourceCaretOffset -= selection.getLength(); IRegion region= fBracketMatcher.match(document, sourceCaretOffset); if (region == null) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } int offset= region.getOffset(); int length= region.getLength(); if (length < 1) return; int anchor= fBracketMatcher.getAnchor(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length; boolean visible= false; if (sourceViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer; visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1); } else { IRegion visibleRegion= sourceViewer.getVisibleRegion(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength()); } if (!visible) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } if (selection.getLength() < 0) targetOffset -= selection.getLength(); sourceViewer.setSelectedRange(targetOffset, selection.getLength()); sourceViewer.revealRange(targetOffset, selection.getLength()); } /** * Ses the given message as error message to this editor's status line. * @param msg message to be set */ protected void setStatusLineErrorMessage(String msg) { IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(true, msg, null); } private static IRegion getSignedSelection(ITextViewer viewer) { StyledText text= viewer.getTextWidget(); int caretOffset= text.getCaretOffset(); Point selection= text.getSelection(); // caret left int offset, length; if (caretOffset == selection.x) { offset= selection.y; length= selection.x - selection.y; // caret right } else { offset= selection.x; length= selection.y - selection.x; } return new Region(offset, length); } private static boolean isBracket(char character) { for (int i= 0; i != BRACKETS.length; ++i) if (character == BRACKETS[i]) return true; return false; } private static boolean isSurroundedByBrackets(IDocument document, int offset) { if (offset == 0 || offset == document.getLength()) return false; try { return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset)); } catch (BadLocationException e) { return false; } } /** * Returns the annotation closest to the given range respecting the given * direction. If an annotation is found, the annotations current position * is copied into the provided annotation position. * * @param offset the region offset * @param length the region length * @param forward <code>true</code> for forwards, <code>false</code> for backward * @param annotationPosition the position of the found annotation * @return the found annotation */ private Annotation getNextAnnotation(int offset, int length, boolean forward, Position annotationPosition) { Annotation nextAnnotation= null; Position nextAnnotationPosition= null; Annotation containingAnnotation= null; Position containingAnnotationPosition= null; boolean currentAnnotation= false; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= 0; IAnnotationAccess access= getAnnotationAccess(); IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= new JavaAnnotationIterator(model, true, true); while (e.hasNext()) { Annotation a= (Annotation) e.next(); Object type; if (a instanceof IJavaAnnotation) type= ((IJavaAnnotation) a).getAnnotationType(); else type= access.getType(a); boolean isNavigationTarget= isNavigationTargetType(type); if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget) continue; Position p= model.getPosition(a); if (p == null) continue; if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.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 (nextAnnotation == null || currentDistance < distance) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } else { if (containingAnnotationPosition == null || containingAnnotationPosition.length > p.length) { containingAnnotation= a; containingAnnotationPosition= p; if (length == p.length) currentAnnotation= true; } } } if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) { annotationPosition.setOffset(containingAnnotationPosition.getOffset()); annotationPosition.setLength(containingAnnotationPosition.getLength()); return containingAnnotation; } if (nextAnnotationPosition != null) { annotationPosition.setOffset(nextAnnotationPosition.getOffset()); annotationPosition.setLength(nextAnnotationPosition.getLength()); } return nextAnnotation; } /** * Returns the annotation overlapping with the given range or <code>null</code>. * * @param offset the region offset * @param length the region length * @return the found annotation or <code>null</code> * @since 3.0 */ private Annotation getAnnotation(int offset, int length) { IAnnotationAccess access= getAnnotationAccess(); IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= new JavaAnnotationIterator(model, true, true); while (e.hasNext()) { Annotation a= (Annotation) e.next(); if (a instanceof IJavaAnnotation) { IJavaAnnotation annotation= (IJavaAnnotation) a; if (annotation.hasOverlay() || !isNavigationTargetType(annotation.getAnnotationType())) continue; } else if (!isNavigationTargetType(access.getType(a))) continue; Position p= model.getPosition(a); if (p != null && p.overlapsWith(offset, length)) return a; } return null; } /** * Returns whether the given annotation type is configured as a target type * for the "Go to Next/Previous Annotation" actions * * @param type the annotation type * @return <code>true</code> if this is a target type, <code>false</code> * otherwise * @since 3.0 */ private boolean isNavigationTargetType(Object type) { Preferences preferences= Platform.getPlugin("org.eclipse.ui.workbench.texteditor").getPluginPreferences(); //$NON-NLS-1$ Iterator i= getAnnotationPreferences().getAnnotationPreferences().iterator(); while (i.hasNext()) { AnnotationPreference annotationPref= (AnnotationPreference) i.next(); if (annotationPref.getAnnotationType().equals(type)) { // See bug 41689 // String key= forward ? annotationPref.getIsGoToNextNavigationTargetKey() : annotationPref.getIsGoToPreviousNavigationTargetKey(); String key= annotationPref.getIsGoToNextNavigationTargetKey(); if (key != null && preferences.getBoolean(key)) return true; } } return false; } /** * Computes and returns the source reference that includes the caret and * serves as provider for the outline page selection and the editor range * indication. * * @return the computed source reference * @since 3.0 */ protected ISourceReference computeHighlightRangeSourceReference() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return null; StyledText styledText= sourceViewer.getTextWidget(); if (styledText == null) return null; int caret= 0; if (sourceViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer; caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); } else { int offset= sourceViewer.getVisibleRegion().getOffset(); caret= offset + styledText.getCaretOffset(); } IJavaElement element= getElementAt(caret, false); 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() == caret) return container; } return (ISourceReference) element; } /** * Returns the most narrow java element including the given offset. * * @param offset the offset inside of the requested element * @param reconcile <code>true</code> if editor input should be reconciled in advance * @return the most narrow java element * @since 3.0 */ protected IJavaElement getElementAt(int offset, boolean reconcile) { return getElementAt(offset); } /* * @see org.eclipse.ui.texteditor.ExtendedTextEditor#createChangeHover() */ protected LineChangeHover createChangeHover() { return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING); } protected boolean isPrefQuickDiffAlwaysOn() { return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } }
44,417
Bug 44417 inline call a field initializer: could detect self reference [refactoring]
20031008 class A { private String fName= getName(); private String getName() { return fName(); } } - inline getName() - it result in fName= fName which does not compile
resolved fixed
a7faa28
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:09:21Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/invalid/TestInvalidFieldInitializer3.java
44,417
Bug 44417 inline call a field initializer: could detect self reference [refactoring]
20031008 class A { private String fName= getName(); private String getName() { return fName(); } } - inline getName() - it result in fName= fName which does not compile
resolved fixed
a7faa28
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:09:21Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui.tests.refactoring/test
44,417
Bug 44417 inline call a field initializer: could detect self reference [refactoring]
20031008 class A { private String fName= getName(); private String getName() { return fName(); } } - inline getName() - it result in fName= fName which does not compile
resolved fixed
a7faa28
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:09:21Z
2003-10-08T13:33:20Z
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
44,417
Bug 44417 inline call a field initializer: could detect self reference [refactoring]
20031008 class A { private String fName= getName(); private String getName() { return fName(); } } - inline getName() - it result in fName= fName which does not compile
resolved fixed
a7faa28
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:09:21Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui/core
44,417
Bug 44417 inline call a field initializer: could detect self reference [refactoring]
20031008 class A { private String fName= getName(); private String getName() { return fName(); } } - inline getName() - it result in fName= fName which does not compile
resolved fixed
a7faa28
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:09:21Z
2003-10-08T13:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
44,417
Bug 44417 inline call a field initializer: could detect self reference [refactoring]
20031008 class A { private String fName= getName(); private String getName() { return fName(); } } - inline getName() - it result in fName= fName which does not compile
resolved fixed
a7faa28
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:09:21Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui/core
44,417
Bug 44417 inline call a field initializer: could detect self reference [refactoring]
20031008 class A { private String fName= getName(); private String getName() { return fName(); } } - inline getName() - it result in fName= fName which does not compile
resolved fixed
a7faa28
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:09:21Z
2003-10-08T13:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceProvider.java
41,489
Bug 41489 [Dialogs] Move resource should filter closed projects
The move resource dialog should either filter closed projects or should offer a functionality to open closed projects. The error message "The selected destination is not accessible" is inadaquate.
closed fixed
61ebc78
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:18:44Z
2003-08-13T15:53:20Z
org.eclipse.jdt.ui/ui
41,489
Bug 41489 [Dialogs] Move resource should filter closed projects
The move resource dialog should either filter closed projects or should offer a functionality to open closed projects. The error message "The selected destination is not accessible" is inadaquate.
closed fixed
61ebc78
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-20T15:18:44Z
2003-08-13T15:53:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/DestinationContentProvider.java
45,260
Bug 45260 Rename package yields newNotPresent Exception
null
resolved fixed
aef55d2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-21T09:34:25Z
2003-10-21T09:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/StandardJavaElementContentProvider.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaElementDelta; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; /** * A base content provider for Java elements. It provides access to the * Java element hierarchy without listening to changes in the Java model. * If updating the presentation on Java model change is required than * clients have to subclass, listen to Java model changes and have to update * the UI using corresponding methods provided by the JFace viewers or their * own UI presentation. * <p> * The following Java element hierarchy is surfaced by this content provider: * <p> * <pre> Java model (<code>IJavaModel</code>) Java project (<code>IJavaProject</code>) package fragment root (<code>IPackageFragmentRoot</code>) package fragment (<code>IPackageFragment</code>) compilation unit (<code>ICompilationUnit</code>) binary class file (<code>IClassFile</code>) * </pre> * </p> * <p> * Note that when the entire Java project is declared to be package fragment root, * the corresponding package fragment root element that normally appears between the * Java project and the package fragments is automatically filtered out. * </p> * This content provider can optionally return working copy elements for members * below compilation units. If enabled, working copy members are returned for those * compilation units in the Java element hierarchy for which a shared working copy exists * in JDT core. * * @see org.eclipse.jdt.ui.IWorkingCopyProvider * @see JavaCore#getSharedWorkingCopies(org.eclipse.jdt.core.IBufferFactory) * * @since 2.0 */ public class StandardJavaElementContentProvider implements ITreeContentProvider, IWorkingCopyProvider { protected static final Object[] NO_CHILDREN= new Object[0]; protected boolean fProvideMembers= false; protected boolean fProvideWorkingCopy= false; /** * Creates a new content provider. The content provider does not * provide members of compilation units or class files and it does * not provide working copy elements. */ public StandardJavaElementContentProvider() { } /** * Creates a new <code>StandardJavaElementContentProvider</code>. * * @param provideMembers if <code>true</code> members below compilation units * and class files are provided. * @param provideWorkingCopy if <code>true</code> the element provider provides * working copies members of compilation units which have an associated working * copy in JDT core. Otherwise only original elements are provided. */ public StandardJavaElementContentProvider(boolean provideMembers, boolean provideWorkingCopy) { fProvideMembers= provideMembers; fProvideWorkingCopy= provideWorkingCopy; } /** * Returns whether members are provided when asking * for a compilation units or class file for its children. * * @return <code>true</code> if the content provider provides members; * otherwise <code>false</code> is returned */ public boolean getProvideMembers() { return fProvideMembers; } /** * Sets whether the content provider is supposed to return members * when asking a compilation unit or class file for its children. * * @param b if <code>true</code> then members are provided. * If <code>false</code> compilation units and class files are the * leaves provided by this content provider. */ public void setProvideMembers(boolean b) { fProvideMembers= b; } /** * Returns whether the provided members are from a working * copy or the original compilation unit. * * @return <code>true</code> if the content provider provides * working copy members; otherwise <code>false</code> is * returned * * @see #setProvideWorkingCopy(boolean) */ public boolean getProvideWorkingCopy() { return fProvideWorkingCopy; } /** * Sets whether the members are provided from a shared working copy * that exists for a original compilation unit in the Java element hierarchy. * * @param b if <code>true</code> members are provided from a * working copy if one exists in JDT core. If <code>false</code> the * provider always returns original elements. */ public void setProvideWorkingCopy(boolean b) { fProvideWorkingCopy= b; } /* (non-Javadoc) * @see IWorkingCopyProvider#providesWorkingCopies() */ public boolean providesWorkingCopies() { return fProvideWorkingCopy; } /* (non-Javadoc) * Method declared on IStructuredContentProvider. */ public Object[] getElements(Object parent) { return getChildren(parent); } /* (non-Javadoc) * Method declared on IContentProvider. */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } /* (non-Javadoc) * Method declared on IContentProvider. */ public void dispose() { } /* (non-Javadoc) * Method declared on ITreeContentProvider. */ public Object[] getChildren(Object element) { if (!exists(element)) return NO_CHILDREN; try { if (element instanceof IJavaModel) return getJavaProjects((IJavaModel)element); if (element instanceof IJavaProject) return getPackageFragmentRoots((IJavaProject)element); if (element instanceof IPackageFragmentRoot) return getPackageFragments((IPackageFragmentRoot)element); if (element instanceof IPackageFragment) return getPackageContents((IPackageFragment)element); if (element instanceof IFolder) return getResources((IFolder)element); if (getProvideMembers() && element instanceof ISourceReference && element instanceof IParent) { if (getProvideWorkingCopy() && element instanceof ICompilationUnit) { element= JavaModelUtil.toWorkingCopy((ICompilationUnit) element); } return ((IParent)element).getChildren(); } } catch (JavaModelException e) { return NO_CHILDREN; } return NO_CHILDREN; } /* (non-Javadoc) * @see ITreeContentProvider */ public boolean hasChildren(Object element) { if (getProvideMembers()) { // assume CUs and class files are never empty if (element instanceof ICompilationUnit || element instanceof IClassFile) { return true; } } else { // don't allow to drill down into a compilation unit or class file if (element instanceof ICompilationUnit || element instanceof IClassFile || element instanceof IFile) return false; } if (element instanceof IJavaProject) { IJavaProject jp= (IJavaProject)element; if (!jp.getProject().isOpen()) { return false; } } if (element instanceof IParent) { try { // when we have Java children return true, else we fetch all the children if (((IParent)element).hasChildren()) return true; } catch(JavaModelException e) { return true; } } Object[] children= getChildren(element); return (children != null) && children.length > 0; } /* (non-Javadoc) * Method declared on ITreeContentProvider. */ public Object getParent(Object element) { if (!exists(element)) return null; return internalGetParent(element); } private Object[] getPackageFragments(IPackageFragmentRoot root) throws JavaModelException { IJavaElement[] fragments= root.getChildren(); Object[] nonJavaResources= root.getNonJavaResources(); if (nonJavaResources == null) return fragments; return concatenate(fragments, nonJavaResources); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException { if (!project.getProject().isOpen()) return NO_CHILDREN; IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); List list= new ArrayList(roots.length); // filter out package fragments that correspond to projects and // replace them with the package fragments directly for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot root= roots[i]; if (isProjectPackageFragmentRoot(root)) { Object[] children= root.getChildren(); for (int k= 0; k < children.length; k++) list.add(children[k]); } else if (hasChildren(root)) { list.add(root); } } return concatenate(list.toArray(), project.getNonJavaResources()); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object[] getJavaProjects(IJavaModel jm) throws JavaModelException { return jm.getJavaProjects(); } private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException { if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) { return concatenate(fragment.getCompilationUnits(), fragment.getNonJavaResources()); } return concatenate(fragment.getClassFiles(), fragment.getNonJavaResources()); } private Object[] getResources(IFolder folder) { try { // filter out folders that are package fragment roots Object[] members= folder.members(); List nonJavaResources= new ArrayList(); for (int i= 0; i < members.length; i++) { Object o= members[i]; // A folder can also be a package fragement root in the following case // Project // + src <- source folder // + excluded <- excluded from class path // + included <- a new source folder. // Included is a member of excluded, but since it is rendered as a source // folder we have to exclude it as a normal child. if (o instanceof IFolder) { IJavaElement element= JavaCore.create((IFolder)o); if (element instanceof IPackageFragmentRoot && element.exists()) { continue; } } nonJavaResources.add(o); } return nonJavaResources.toArray(); } catch(CoreException e) { return NO_CHILDREN; } } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean isClassPathChange(IJavaElementDelta delta) { // need to test the flags only for package fragment roots if (delta.getElement().getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) return false; int flags= delta.getFlags(); return (delta.getKind() == IJavaElementDelta.CHANGED && ((flags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) || ((flags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) || ((flags & IJavaElementDelta.F_REORDER) != 0)); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object skipProjectPackageFragmentRoot(IPackageFragmentRoot root) { try { if (isProjectPackageFragmentRoot(root)) return root.getParent(); return root; } catch(JavaModelException e) { return root; } } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean isPackageFragmentEmpty(IJavaElement element) throws JavaModelException { if (element instanceof IPackageFragment) { IPackageFragment fragment= (IPackageFragment)element; if (fragment.exists() || !(fragment.hasChildren() || fragment.getNonJavaResources().length > 0) && fragment.hasSubpackages()) return true; } return false; } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) throws JavaModelException { IResource resource= root.getResource(); return (resource instanceof IProject); } /** * Note: This method is for internal use only. Clients should not call this method. */ protected boolean exists(Object element) { if (element == null) { return false; } if (element instanceof IResource) { return ((IResource)element).exists(); } if (element instanceof IJavaElement) { return ((IJavaElement)element).exists(); } return true; } /** * Note: This method is for internal use only. Clients should not call this method. */ protected Object internalGetParent(Object element) { if (element instanceof IJavaProject) { return ((IJavaProject)element).getJavaModel(); } // try to map resources to the containing package fragment if (element instanceof IResource) { IResource parent= ((IResource)element).getParent(); IJavaElement jParent= JavaCore.create(parent); // http://bugs.eclipse.org/bugs/show_bug.cgi?id=31374 if (jParent != null && jParent.exists()) return jParent; return parent; } // for package fragments that are contained in a project package fragment // we have to skip the package fragment root as the parent. if (element instanceof IPackageFragment) { IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent(); return skipProjectPackageFragmentRoot(parent); } if (element instanceof IJavaElement) { IJavaElement candidate= ((IJavaElement)element).getParent(); // If the parent is a CU we might have shown working copy elements below CU level. If so // return the original element instead of the working copy. if (candidate != null && candidate.getElementType() == IJavaElement.COMPILATION_UNIT) { candidate= JavaModelUtil.toOriginal((ICompilationUnit) candidate); } return candidate; } return null; } /** * Note: This method is for internal use only. Clients should not call this method. */ protected static Object[] concatenate(Object[] a1, Object[] a2) { int a1Len= a1.length; int a2Len= a2.length; Object[] res= new Object[a1Len + a2Len]; System.arraycopy(a1, 0, res, 0, a1Len); System.arraycopy(a2, 0, res, a1Len, a2Len); return res; } }
45,259
Bug 45259 Bug in DocumentAdapter2.validateLineDelimiters
Version: 3.0.0 Build id: 200310150800 When I try to replace part of text in IBuffer and if this text contains new line delimiter, for example under Linux I open file with \r\n and convert it in \n, I see two exceptions, first about new line delimiter and second as result of bug. Look in inner loop, you have loop by 'k', but access to character using 'i'. Can you please fix this and allow plugins to replace parts of text with new delimiters without additional exceptions in log? for (int i= 0; i < lines; i++) { try { String curr= tracker.getLineDelimiter(i); if (curr != null && !fLegalLineDelimiters.contains(curr)) { StringBuffer buf= new StringBuffer("New line delimiter added to new code: "); //$NON-NLS-1$ for (int k= 0; k < curr.length(); k++) { buf.append(String.valueOf((int) curr.charAt(i))); } JavaPlugin.log(new Exception(buf.toString())); } } catch (BadLocationException e) { JavaPlugin.log(e); } } java.lang.Exception: New line delimiter added to new code: 10 at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.DocumentAdapter2.validateLineDelimiters(DocumentAdapter2.java:430) at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.DocumentAdapter2.setContents(DocumentAdapter2.java:383) at com.swtdesigner.gef.DesignerEditor.handleActivate(DesignerEditor.java:259) at com.swtdesigner.editors.MultiPageEditor.showDesignEditor(MultiPageEditor.java:82) at com.swtdesigner.editors.MultiPageEditor$1.widgetSelected(MultiPageEditor.java:30) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:1739) at org.eclipse.swt.custom.CTabFolder.onMouseDown(CTabFolder.java:1927) at org.eclipse.swt.custom.CTabFolder.access$4(CTabFolder.java:1919) at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:201) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2361) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2344) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599) java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.charAt(String.java:444) at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.DocumentAdapter2.validateLineDelimiters(DocumentAdapter2.java:428) at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.DocumentAdapter2.setContents(DocumentAdapter2.java:383) at com.swtdesigner.gef.DesignerEditor.handleActivate(DesignerEditor.java:259) at com.swtdesigner.editors.MultiPageEditor.showDesignEditor(MultiPageEditor.java:82) at com.swtdesigner.editors.MultiPageEditor$1.widgetSelected(MultiPageEditor.java:30) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:1739) at org.eclipse.swt.custom.CTabFolder.onMouseDown(CTabFolder.java:1927) at org.eclipse.swt.custom.CTabFolder.access$4(CTabFolder.java:1919) at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:201) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2361) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2344) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
resolved fixed
c857d4e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-21T09:56:10Z
2003-10-21T09:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/filebuffers/DocumentAdapter2.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor.filebuffers; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.filebuffers.FileBuffers; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; 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.swt.widgets.Display; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultLineTracker; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jdt.core.BufferChangedEvent; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.IBufferChangedListener; import org.eclipse.jdt.core.IOpenable; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Adapts <code>IDocument</code> to <code>IBuffer</code>. Uses the * same algorithm as the text widget to determine the buffer's line delimiter. * All text inserted into the buffer is converted to this line delimiter. * This class is <code>public</code> for test purposes only. */ public class DocumentAdapter2 implements IBuffer, IDocumentListener { /** * Internal implementation of a NULL instanceof IBuffer. */ static private class NullBuffer implements IBuffer { public void addBufferChangedListener(IBufferChangedListener listener) {} public void append(char[] text) {} public void append(String text) {} public void close() {} public char getChar(int position) { return 0; } public char[] getCharacters() { return null; } public String getContents() { return null; } public int getLength() { return 0; } public IOpenable getOwner() { return null; } public String getText(int offset, int length) { return null; } public IResource getUnderlyingResource() { return null; } public boolean hasUnsavedChanges() { return false; } public boolean isClosed() { return false; } public boolean isReadOnly() { return true; } public void removeBufferChangedListener(IBufferChangedListener listener) {} public void replace(int position, int length, char[] text) {} public void replace(int position, int length, String text) {} public void save(IProgressMonitor progress, boolean force) throws JavaModelException {} public void setContents(char[] contents) {} public void setContents(String contents) {} } /** NULL implementing <code>IBuffer</code> */ public final static IBuffer NULL= new NullBuffer(); /** * Executes a document set content call in the ui thread. */ protected class DocumentSetCommand implements Runnable { private String fContents; public void run() { fDocument.set(fContents); } public void set(String contents) { fContents= contents; Display.getDefault().syncExec(this); } } /** * Executes a document replace call in the ui thread. */ protected class DocumentReplaceCommand implements Runnable { private int fOffset; private int fLength; private String fText; public void run() { try { fDocument.replace(fOffset, fLength, fText); } catch (BadLocationException x) { // ignore } } public void replace(int offset, int length, String text) { fOffset= offset; fLength= length; fText= text; Display.getDefault().syncExec(this); } } private static final boolean DEBUG_LINE_DELIMITERS= true; private IOpenable fOwner; private IFile fFile; private ITextFileBuffer fTextFileBuffer; private IDocument fDocument; private DocumentSetCommand fSetCmd= new DocumentSetCommand(); private DocumentReplaceCommand fReplaceCmd= new DocumentReplaceCommand(); private Set fLegalLineDelimiters; private List fBufferListeners= new ArrayList(3); private IStatus fStatus; /** * This method is <code>public</code> for test purposes only. */ public DocumentAdapter2(IOpenable owner, IFile file) { fOwner= owner; fFile= file; initialize(); } private void initialize() { ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); IPath location= fFile.getLocation(); try { manager.connect(location, new NullProgressMonitor()); fTextFileBuffer= manager.getTextFileBuffer(location); fDocument= fTextFileBuffer.getDocument(); } catch (CoreException x) { fStatus= x.getStatus(); fDocument= manager.createEmptyDocument(location); } fDocument.addPrenotifiedDocumentListener(this); } /** * Returns the status of this document adapter. */ public IStatus getStatus() { if (fStatus != null) return fStatus; if (fTextFileBuffer != null) return fTextFileBuffer.getStatus(); return null; } /** * Returns the adapted document. * * @return the adapted document */ public IDocument getDocument() { return fDocument; } /* * @see IBuffer#addBufferChangedListener(IBufferChangedListener) */ public void addBufferChangedListener(IBufferChangedListener listener) { Assert.isNotNull(listener); if (!fBufferListeners.contains(listener)) fBufferListeners.add(listener); } /* * @see IBuffer#removeBufferChangedListener(IBufferChangedListener) */ public void removeBufferChangedListener(IBufferChangedListener listener) { Assert.isNotNull(listener); fBufferListeners.remove(listener); } /* * @see IBuffer#append(char[]) */ public void append(char[] text) { append(new String(text)); } /* * @see IBuffer#append(String) */ public void append(String text) { if (DEBUG_LINE_DELIMITERS) { validateLineDelimiters(text); } fReplaceCmd.replace(fDocument.getLength(), 0, text); } /* * @see IBuffer#close() */ public void close() { if (isClosed()) return; IDocument d= fDocument; fDocument= null; d.removePrenotifiedDocumentListener(this); if (fTextFileBuffer != null) { ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); try { manager.disconnect(fTextFileBuffer.getLocation(), new NullProgressMonitor()); } catch (CoreException x) { // ignore } fTextFileBuffer= null; } fireBufferChanged(new BufferChangedEvent(this, 0, 0, null)); fBufferListeners.clear(); } /* * @see IBuffer#getChar(int) */ public char getChar(int position) { try { return fDocument.getChar(position); } catch (BadLocationException x) { throw new ArrayIndexOutOfBoundsException(); } } /* * @see IBuffer#getCharacters() */ public char[] getCharacters() { String content= getContents(); return content == null ? null : content.toCharArray(); } /* * @see IBuffer#getContents() */ public String getContents() { return fDocument.get(); } /* * @see IBuffer#getLength() */ public int getLength() { return fDocument.getLength(); } /* * @see IBuffer#getOwner() */ public IOpenable getOwner() { return fOwner; } /* * @see IBuffer#getText(int, int) */ public String getText(int offset, int length) { try { return fDocument.get(offset, length); } catch (BadLocationException x) { throw new ArrayIndexOutOfBoundsException(); } } /* * @see IBuffer#getUnderlyingResource() */ public IResource getUnderlyingResource() { return fFile; } /* * @see IBuffer#hasUnsavedChanges() */ public boolean hasUnsavedChanges() { return fTextFileBuffer != null ? fTextFileBuffer.isDirty() : false; } /* * @see IBuffer#isClosed() */ public boolean isClosed() { return fDocument == null; } /* * @see IBuffer#isReadOnly() */ public boolean isReadOnly() { IResource resource= getUnderlyingResource(); return resource == null ? true : resource.isReadOnly(); } /* * @see IBuffer#replace(int, int, char[]) */ public void replace(int position, int length, char[] text) { replace(position, length, new String(text)); } /* * @see IBuffer#replace(int, int, String) */ public void replace(int position, int length, String text) { if (DEBUG_LINE_DELIMITERS) { validateLineDelimiters(text); } fReplaceCmd.replace(position, length, text); } /* * @see IBuffer#save(IProgressMonitor, boolean) */ public void save(IProgressMonitor progress, boolean force) throws JavaModelException { try { if (fTextFileBuffer != null) fTextFileBuffer.commit(progress, force); } catch (CoreException e) { throw new JavaModelException(e); } } /* * @see IBuffer#setContents(char[]) */ public void setContents(char[] contents) { setContents(new String(contents)); } /* * @see IBuffer#setContents(String) */ public void setContents(String contents) { int oldLength= fDocument.getLength(); if (contents == null) { if (oldLength != 0) fSetCmd.set(""); //$NON-NLS-1$ } else { // set only if different if (DEBUG_LINE_DELIMITERS) { validateLineDelimiters(contents); } if (!contents.equals(fDocument.get())) fSetCmd.set(contents); } } private void validateLineDelimiters(String contents) { if (fLegalLineDelimiters == null) { // collect all line delimiters in the document HashSet existingDelimiters= new HashSet(); for (int i= fDocument.getNumberOfLines() - 1; i >= 0; i-- ) { try { String curr= fDocument.getLineDelimiter(i); if (curr != null) { existingDelimiters.add(curr); } } catch (BadLocationException e) { JavaPlugin.log(e); } } if (existingDelimiters.isEmpty()) { return; // first insertion of a line delimiter: no test } fLegalLineDelimiters= existingDelimiters; } DefaultLineTracker tracker= new DefaultLineTracker(); tracker.set(contents); int lines= tracker.getNumberOfLines(); if (lines <= 1) return; for (int i= 0; i < lines; i++) { try { String curr= tracker.getLineDelimiter(i); if (curr != null && !fLegalLineDelimiters.contains(curr)) { StringBuffer buf= new StringBuffer("New line delimiter added to new code: "); //$NON-NLS-1$ for (int k= 0; k < curr.length(); k++) { buf.append(String.valueOf((int) curr.charAt(i))); } JavaPlugin.log(new Exception(buf.toString())); } } catch (BadLocationException e) { JavaPlugin.log(e); } } } /* * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { // there is nothing to do here } /* * @see IDocumentListener#documentChanged(DocumentEvent) */ public void documentChanged(DocumentEvent event) { fireBufferChanged(new BufferChangedEvent(this, event.getOffset(), event.getLength(), event.getText())); } private void fireBufferChanged(BufferChangedEvent event) { if (fBufferListeners != null && fBufferListeners.size() > 0) { Iterator e= new ArrayList(fBufferListeners).iterator(); while (e.hasNext()) ((IBufferChangedListener) e.next()).bufferChanged(event); } } }
45,347
Bug 45347 [formatter] Code format comment /*- (java standard do not format comment)
null
resolved fixed
42558e9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-23T14:56:40Z
2003-10-22T08:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentLine.java
/***************************************************************************** * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *****************************************************************************/ package org.eclipse.jdt.internal.ui.text.comment; import java.util.LinkedList; /** * General comment line in a comment region. * * @since 3.0 */ public abstract class CommentLine implements IBorderAttributes { /** The javadoc attributes of this line */ private int fAttributes= 0; /** The region this comment line belongs to */ private final CommentRegion fParent; /** The sequence of comment ranges in this comment line */ private final LinkedList fRanges= new LinkedList(); /** * Creates a new comment line. * * @param region * Comment region to create the line for */ protected CommentLine(final CommentRegion region) { fParent= region; } /** * Gets the context information from the previous comment line and sets it * for the current one. * * @param previous * The previous comment line in the associated comment region */ protected abstract void adapt(final CommentLine previous); /** * Appends the comment range to this comment line. * * @param range * Comment range to append */ protected void append(final CommentRange range) { fRanges.add(range); } /** * Applies the formatted lower border to the underlying document. * * @param range * Last comment range in the comment region * @param indentation * Indenation of the formatted lower border * @param length * The maximal length of text in this comment region measured in * average character widths */ protected void applyEnd(final CommentRange range, final String indentation, final int length) { final int offset= range.getOffset() + range.getLength(); final StringBuffer buffer= new StringBuffer(length); final String end= getEndingPrefix(); final String delimiter= fParent.getDelimiter(); if (fParent.isSingleLine() && fParent.getSize() == 1) buffer.append(end); else { final String filler= getContentPrefix().trim(); buffer.append(delimiter); buffer.append(indentation); if (fParent.hasBorder(BORDER_LOWER)) { buffer.append(' '); for (int character= 0; character < length; character++) buffer.append(filler); buffer.append(end.trim()); } else buffer.append(end); } fParent.applyText(buffer.toString(), offset, fParent.getLength() - offset); } /** * Applies the formatted comment line to the underlying document. * * @param predecessor * The comment line predecessor of this line * @param last * The most recently applied comment range of the previous * comment line in the comment region * @param indentation * Indentation of the formatted comment line * @param line * The index of the comment line in the comment region * @return The first comment range in this comment line */ protected CommentRange applyLine(final CommentLine predecessor, final CommentRange last, final String indentation, final int line) { int offset= 0; int length= 0; CommentRange next= last; CommentRange previous= null; final int stop= fRanges.size() - 1; final int end= fParent.getSize() - 1; for (int index= stop; index >= 0; index--) { previous= next; next= (CommentRange)fRanges.get(index); if (fParent.canApply(previous, next)) { offset= next.getOffset() + next.getLength(); length= previous.getOffset() - offset; if (index == stop && line != end) fParent.applyText(fParent.getDelimiter(predecessor, this, previous, next, indentation), offset, length); else fParent.applyText(fParent.getDelimiter(previous, next), offset, length); } } return next; } /** * Applies the formatted upper border to the underlying document. * * @param range * First comment range in the comment region * @param indentation * Indentation of the formatted upper border * @param length * The maximal length of text in this comment region measured in * average character widths */ protected void applyStart(final CommentRange range, final String indentation, final int length) { final StringBuffer buffer= new StringBuffer(length); final String start= getStartingPrefix(); final String content= getContentPrefix(); if (fParent.isSingleLine() && fParent.getSize() == 1) buffer.append(start); else { final String trimmed= start.trim(); final String filler= content.trim(); buffer.append(trimmed); if (fParent.hasBorder(BORDER_UPPER)) { for (int character= 0; character < length - trimmed.length() + start.length(); character++) buffer.append(filler); } buffer.append(fParent.getDelimiter()); buffer.append(indentation); buffer.append(content); } fParent.applyText(buffer.toString(), 0, range.getOffset()); } /** * Returns the line prefix of content lines. * * @return Line prefix of content lines */ protected abstract String getContentPrefix(); /** * Returns the line prefix of end lines. * * @return Line prefix of end lines */ protected abstract String getEndingPrefix(); /** * Returns the first comment range in this comment line. * * @return The first comment range */ protected final CommentRange getFirst() { return (CommentRange)fRanges.getFirst(); } /** * Returns the indentation reference string for this line. * * @return The indentation reference string for this line */ protected String getIndentation() { return ""; //$NON-NLS-1$ } /** * Returns the last comment range in this comment line. * * @return The last comment range */ protected final CommentRange getLast() { return (CommentRange)fRanges.getLast(); } /** * Returns the parent comment region of this comment line. * * @return The parent comment region */ protected final CommentRegion getParent() { return fParent; } /** * Returns the number of comment ranges in this comment line. * * @return The number of ranges in this line */ protected final int getSize() { return fRanges.size(); } /** * Returns the line prefix of start lines. * * @return Line prefix of start lines */ protected abstract String getStartingPrefix(); /** * Is the attribute <code>attribute</code> true? * * @param attribute * The attribute to get. * @return <code>true</code> iff this attribute is <code>true</code>, * <code>false</code> otherwise. */ protected final boolean hasAttribute(final int attribute) { return (fAttributes & attribute) == attribute; } /** * Scans this line in the comment region. * * @param line * Index of this line in the comment region */ protected abstract void scanLine(final int line); /** * Set the attribute <code>attribute</code> to true. * * @param attribute * The attribute to set. */ protected final void setAttribute(final int attribute) { fAttributes |= attribute; } /** * Tokenizes this line into token ranges. * * @param line * Index of this line in the comment region */ protected void tokenizeLine(final int line) { int offset= 0; int index= offset; final CommentRange range= (CommentRange)fRanges.get(0); final int begin= range.getOffset(); final String content= fParent.getText(begin, range.getLength()); final int length= content.length(); while (offset < length) { while (offset < length && Character.isWhitespace(content.charAt(offset))) offset++; index= offset; while (index < length && !Character.isWhitespace(content.charAt(index))) index++; if (index - offset > 0) { fParent.append(new CommentRange(begin + offset, index - offset)); offset= index; } } } }
45,347
Bug 45347 [formatter] Code format comment /*- (java standard do not format comment)
null
resolved fixed
42558e9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-23T14:56:40Z
2003-10-22T08:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentRegion.java
/***************************************************************************** * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *****************************************************************************/ package org.eclipse.jdt.internal.ui.text.comment; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.GC; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.ConfigurableLineTracker; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jdt.ui.PreferenceConstants; /** * Comment region in a source code document. * * @since 3.0 */ public class CommentRegion extends TypedPosition implements IHtmlTagConstants, IBorderAttributes, ICommentAttributes { /** Position category of comment regions */ protected static final String COMMENT_POSITION_CATEGORY= "__comment_position"; //$NON-NLS-1$ /** Default line prefix length */ public static final int COMMENT_PREFIX_LENGTH= 3; /** Default range delimiter */ protected static final String COMMENT_RANGE_DELIMITER= " "; //$NON-NLS-1$ /** The borders of this range */ private int fBorders= 0; /** Should all blank lines be cleared during formatting? */ private final boolean fClear; /** The line delimiter used in this comment region */ private final String fDelimiter; /** The document to format */ private final IDocument fDocument; /** Graphics context for non-monospace fonts */ private final GC fGraphics; /** The sequence of lines in this comment region */ private final LinkedList fLines= new LinkedList(); /** The sequence of comment ranges in this comment region */ private final LinkedList fRanges= new LinkedList(); /** Is this comment region a single line region? */ private final boolean fSingleLine; /** The comment formatting strategy for this comment region */ private final CommentFormattingStrategy fStrategy; /** Number of characters representing tabulator */ private final int fTabs; /** * Creates a new comment region. * * @param strategy * The comment formatting strategy used to format this comment * region * @param position * The typed position which forms this comment region * @param delimiter * The line delimiter to use in this comment region */ protected CommentRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) { super(position.getOffset(), position.getLength(), position.getType()); fStrategy= strategy; fDelimiter= delimiter; fClear= fStrategy.getPreferences().get(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES) == IPreferenceStore.TRUE; final ISourceViewer viewer= strategy.getViewer(); final StyledText text= viewer.getTextWidget(); fDocument= viewer.getDocument(); if (text != null && !text.isDisposed()) { fGraphics= new GC(text); fGraphics.setFont(text.getFont()); fTabs= text.getTabs(); } else { fGraphics= null; fTabs= 4; } final ILineTracker tracker= new ConfigurableLineTracker(new String[] { delimiter }); IRegion range= null; CommentLine line= null; tracker.set(getText(0, getLength())); final int lines= tracker.getNumberOfLines(); fSingleLine= lines == 1; try { for (int index= 0; index < lines; index++) { range= tracker.getLineInformation(index); line= CommentObjectFactory.createLine(this); line.append(new CommentRange(range.getOffset(), range.getLength())); fLines.add(line); } } catch (BadLocationException exception) { // Should not happen } } /** * Appends the comment range to this comment region. * * @param range * Comment range to append to this comment region */ protected final void append(final CommentRange range) { fRanges.addLast(range); } /** * Applies the formatted comment region to the underlying document. * * @param indentation * Indentation of the formatted comment region * @param width * The maximal width of text in this comment region measured in * average character widths */ protected void applyRegion(final String indentation, final int width) { final int last= fLines.size() - 1; if (last >= 0) { CommentLine previous= null; CommentLine next= (CommentLine)fLines.get(last); CommentRange range= next.getLast(); next.applyEnd(range, indentation, width); for (int line= last; line >= 0; line--) { previous= next; next= (CommentLine)fLines.get(line); range= next.applyLine(previous, range, indentation, line); } next.applyStart(range, indentation, width); } } /** * Applies the changed content to the underlying document * * @param change * Text content to apply to the underlying document * @param position * Offset measured in comment region coordinates where to apply * the changed content * @param count * Length of the content to be changed */ protected final void applyText(final String change, final int position, final int count) { try { final int base= getOffset() + position; final String content= fDocument.get(base, count); if (!change.equals(content)) fDocument.replace(getOffset() + position, count, change); } catch (BadLocationException exception) { // Should not happen } } /** * Can the comment range be appended to the comment line? * * @param line * Comment line where to append the comment range * @param previous * Comment range which is the predecessor of the current comment * range * @param next * Comment range to test whether it can be appended to the * comment line * @param space * Amount of space in the comment line used by already inserted * comment ranges * @param width * The maximal width of text in this comment region measured in * average character widths * @return <code>true</code> iff the comment range can be added to the * line, <code>false</code> otherwise */ protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int space, final int width) { return space == 0 || space + next.getLength() < width; } /** * Can the two current comment ranges be applied to the underlying * document? * * @param previous * Previous comment range which was already applied * @param next * Next comment range to be applied * @return <code>true</code> iff the next comment range can be applied, * <code>false</code> otherwise */ protected boolean canApply(final CommentRange previous, final CommentRange next) { return true; } /** * Finalizes the comment region and adjusts its starting indentation. * * @param indentation * Indentation of the formatted comment region */ protected void finalizeRegion(final String indentation) { // Do nothing } /** * Formats the comment region. * * @param indentation * Indentation of the formatted comment region */ public void format(String indentation) { final Map preferences= fStrategy.getPreferences(); int margin= 80; try { margin= Integer.parseInt(preferences.get(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH).toString()); } catch (Exception exception) { // Do nothing } margin= Math.max(COMMENT_PREFIX_LENGTH + 1, margin - stringToLength(indentation) - COMMENT_PREFIX_LENGTH); fDocument.addPositionCategory(COMMENT_POSITION_CATEGORY); final IPositionUpdater positioner= new DefaultPositionUpdater(COMMENT_POSITION_CATEGORY); fDocument.addPositionUpdater(positioner); try { initializeRegion(); markRegion(); wrapRegion(margin); applyRegion(indentation, margin); finalizeRegion(indentation); } finally { if (fGraphics != null && !fGraphics.isDisposed()) fGraphics.dispose(); try { fDocument.removePositionCategory(COMMENT_POSITION_CATEGORY); fDocument.removePositionUpdater(positioner); } catch (BadPositionCategoryException exception) { // Should not happen } } } /** * Returns the general line delimiter used in this comment region. * * @return The line delimiter for this comment region */ protected final String getDelimiter() { return fDelimiter; } /** * Returns the line delimiter used in this comment line break. * * @param predecessor * The predecessor comment line before the line break * @param successor * The successor comment line after the line break * @param previous * The comment range after the line break * @param next * The comment range before the line break * @param indentation * Indentation of the formatted line break * @return The line delimiter for this comment line break */ protected String getDelimiter(final CommentLine predecessor, final CommentLine successor, final CommentRange previous, final CommentRange next, final String indentation) { return fDelimiter + indentation + successor.getContentPrefix(); } /** * Returns the range delimiter for this comment range break in this comment * region. * * @param previous * The previous comment range to the right of the range delimiter * @param next * The next comment range to the left of the range delimiter * @return The delimiter for this comment range break */ protected String getDelimiter(final CommentRange previous, final CommentRange next) { return COMMENT_RANGE_DELIMITER; } /** * Returns the document of this comment region. * * @return The document of this region */ protected final IDocument getDocument() { return fDocument; } /** * Returns the list of comment ranges in this comment region * * @return The list of comment ranges in this region */ protected final LinkedList getRanges() { return fRanges; } /** * Returns the number of comment lines in this comment region. * * @return The number of lines in this comment region */ protected final int getSize() { return fLines.size(); } /** * Returns the comment formatting strategy used to format this comment * region. * * @return The formatting strategy for this comment region */ protected final CommentFormattingStrategy getStrategy() { return fStrategy; } /** * Returns the text of this comment region in the indicated range. * * @param position * The offset of the comment range to retrieve in comment region * coordinates * @param count * The length of the comment range to retrieve * @return The content of this comment region in the indicated range */ protected final String getText(final int position, final int count) { String content= ""; //$NON-NLS-1$ try { content= fDocument.get(getOffset() + position, count); } catch (BadLocationException exception) { // Should not happen } return content; } /** * Does the border <code>border</code> exist? * * @param border * The type of the border. Must be a border attribute of <code>CommentRegion</code>. * @return <code>true</code> iff this border exists, <code>false</code> * otherwise. */ protected final boolean hasBorder(final int border) { return (fBorders & border) == border; } /** * Initializes the internal representation of the comment region. */ protected void initializeRegion() { try { fDocument.addPosition(COMMENT_POSITION_CATEGORY, this); } catch (BadLocationException exception) { // Should not happen } catch (BadPositionCategoryException exception) { // Should not happen } int index= 0; CommentLine line= null; for (final Iterator iterator= fLines.iterator(); iterator.hasNext(); index++) { line= (CommentLine)iterator.next(); line.scanLine(index); line.tokenizeLine(index); } } /** * Should blank lines be cleared during formatting? * * @return <code>true</code> iff blank lines should be cleared, <code>false</code> * otherwise */ protected final boolean isClearLines() { return fClear; } /** * Is the current comment range a word? * * @param current * Comment range to test whether it is a word * @return <code>true</code> iff the comment range is a word, <code>false</code> * otherwise. */ protected final boolean isCommentWord(final CommentRange current) { final String token= getText(current.getOffset(), current.getLength()); for (int index= 0; index < token.length(); index++) { if (!Character.isLetterOrDigit(token.charAt(index))) return false; } return true; } /** * Is this comment region a single line region? * * @return <code>true</code> iff this region is single line, <code>false</code> * otherwise. */ protected final boolean isSingleLine() { return fSingleLine; } /** * Marks the attributed ranges in this comment region. */ protected void markRegion() { // Do nothing } /** * Set the border <code>border</code> to true. * * @param border * The type of the border. Must be a border attribute of <code>CommentRegion</code>. */ protected final void setBorder(final int border) { fBorders |= border; } /** * Returns the indentation string for a reference string * * @param reference * The reference string to get the indentation string for * @param tabs * <code>true</code> iff the indent should use tabs, <code>false</code> * otherwise. * @return The indentation string */ protected final String stringToIndent(final String reference, final boolean tabs) { int space= 1; int pixels= reference.length(); if (fGraphics != null) { pixels= stringToPixels(reference); space= fGraphics.stringExtent(" ").x; //$NON-NLS-1$ } final StringBuffer buffer= new StringBuffer(); final int spaces= pixels / space; if (tabs) { final int count= spaces / fTabs; final int modulo= spaces % fTabs; for (int index= 0; index < count; index++) buffer.append('\t'); for (int index= 0; index < modulo; index++) buffer.append(' '); } else { for (int index= 0; index < spaces; index++) buffer.append(' '); } return buffer.toString(); } /** * Returns the length of the reference string in characters. * * @param reference * The reference string to get the length * @return The length of the string in characters */ protected final int stringToLength(final String reference) { int tabs= 0; int count= reference.length(); for (int index= 0; index < count; index++) { if (reference.charAt(index) == '\t') tabs++; } count += tabs * (fTabs - 1); return count; } /** * Returns the width of the reference string in pixels. * * @param reference * The reference string to get the width * @return The width of the string in pixels */ protected final int stringToPixels(final String reference) { final StringBuffer buffer= new StringBuffer(); char character= 0; for (int index= 0; index < reference.length(); index++) { character= reference.charAt(index); if (character == '\t') { for (int tab= 0; tab < fTabs; tab++) buffer.append(' '); } else buffer.append(character); } return fGraphics.stringExtent(buffer.toString()).x; } /** * Wraps the comment ranges in this comment region into comment lines. * * @param width * The maximal width of text in this comment region measured in * average character widths */ protected void wrapRegion(final int width) { fLines.clear(); int index= 0; boolean adapted= false; CommentLine successor= null; CommentLine predecessor= null; CommentRange previous= null; CommentRange next= null; while (!fRanges.isEmpty()) { index= 0; adapted= false; predecessor= successor; successor= CommentObjectFactory.createLine(this); fLines.add(successor); while (!fRanges.isEmpty()) { next= (CommentRange)fRanges.getFirst(); if (canAppend(successor, previous, next, index, width)) { if (!adapted && predecessor != null) { successor.adapt(predecessor); adapted= true; } fRanges.removeFirst(); successor.append(next); index += (next.getLength() + 1); previous= next; } else break; } } } }
45,446
Bug 45446 [Outline] 'Hide Fields' option not saved b/w editors
I20031023 - new/clean workspace - checkout platform-ui projects and compile - Java Perspective - open a class (ProblemView) - in Outline view, click the buttons 'Hide Field' (so you don't see the fields) and 'Sort'(so methods appear in alphabetical order) - Outline view is updated - open another class (SelectionEnabler) - note that the 'Sort' button is depressed in the Outline view but the 'Hide Fields' button is not (so you see the fields) - click on 'Hide Fields' and the fields are hidden - open a 3rd Java class (PluginAction) - 'Sort' button is depressed but 'Hide Fields' is not - I wasn't dreaming the first time!
resolved fixed
cb21594
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-23T15:55:22Z
2003-10-23T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/MemberFilterActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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 java.util.ArrayList; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.jface.action.IMenuManager; 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.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.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 hide non-public members and hide local types. * <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; /** @since 3.0 */ public static final int FILTER_LOCALTYPES= MemberFilter.FILTER_LOCALTYPES; /** @since 3.0 */ public static final int ALL_FILTERS= FILTER_NONPUBLIC | FILTER_FIELDS | FILTER_STATIC | FILTER_LOCALTYPES; private static final String TAG_HIDEFIELDS= "hidefields"; //$NON-NLS-1$ private static final String TAG_HIDESTATIC= "hidestatic"; //$NON-NLS-1$ private static final String TAG_HIDENONPUBLIC= "hidenonpublic"; //$NON-NLS-1$ private static final String TAG_HIDELOCALTYPES= "hidelocaltypes"; //$NON-NLS-1$ private MemberFilterAction[] fFilterActions; private MemberFilter fFilter; private StructuredViewer fViewer; private String fViewerId; private boolean fInViewMenu; /** * 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) { this(viewer, viewerId, false); } /** * 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 * @param inViewMenu if <code>true</code> the actions are added to the view * menu. If <code>false</code> they are added to the toobar. * * @since 2.1 */ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, boolean inViewMenu) { this(viewer, viewerId, inViewMenu, ALL_FILTERS); } /** * 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 * @param inViewMenu if <code>true</code> the actions are added to the view * menu. If <code>false</code> they are added to the toobar. * @param availableFilters Specifies which filter action should be contained. <code>FILTER_NONPUBLIC</code>, * <code>FILTER_STATIC</code>, <code>FILTER_FIELDS</code> and <code>FILTER_LOCALTYPES</code> * or a combination of these constants are possible values. Use <code>ALL_FILTERS</code> to select all available filters. * * @since 3.0 */ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, boolean inViewMenu, int availableFilters) { fViewer= viewer; fViewerId= viewerId; fInViewMenu= inViewMenu; IPreferenceStore store= PreferenceConstants.getPreferenceStore(); fFilter= new MemberFilter(); String title, helpContext; ArrayList actions= new ArrayList(4); // fields int filterProperty= FILTER_FIELDS; if (isSet(filterProperty, availableFilters)) { boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty)); if (filterEnabled) { fFilter.addFilter(filterProperty); } title= ActionMessages.getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_FIELDS_ACTION; MemberFilterAction hideFields= new MemberFilterAction(this, title, filterProperty, helpContext, filterEnabled); 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$ actions.add(hideFields); } // static filterProperty= FILTER_STATIC; if (isSet(filterProperty, availableFilters)) { boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty)); if (filterEnabled) { fFilter.addFilter(filterProperty); } title= ActionMessages.getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_STATIC_ACTION; MemberFilterAction hideStatic= new MemberFilterAction(this, title, FILTER_STATIC, helpContext, filterEnabled); 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$ actions.add(hideStatic); } // non-public filterProperty= FILTER_NONPUBLIC; if (isSet(filterProperty, availableFilters)) { boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty)); if (filterEnabled) { fFilter.addFilter(filterProperty); } title= ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_PUBLIC_ACTION; MemberFilterAction hideNonPublic= new MemberFilterAction(this, title, filterProperty, helpContext, filterEnabled); 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$ actions.add(hideNonPublic); } // local types filterProperty= FILTER_LOCALTYPES; if (isSet(filterProperty, availableFilters)) { boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty)); if (filterEnabled) { fFilter.addFilter(filterProperty); } title= ActionMessages.getString("MemberFilterActionGroup.hide_localtypes.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_LOCALTYPES_ACTION; MemberFilterAction hideLocalTypes= new MemberFilterAction(this, title, filterProperty, helpContext, filterEnabled); hideLocalTypes.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_localtypes.description")); //$NON-NLS-1$ hideLocalTypes.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_localtypes.tooltip")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideLocalTypes, "localtypes_co.gif"); //$NON-NLS-1$ actions.add(hideLocalTypes); } // order corresponds to order in toolbar fFilterActions= (MemberFilterAction[]) actions.toArray(new MemberFilterAction[actions.size()]); 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> <code>FILTER_PRIVATE</code> and <code>FILTER_LOCALTYPES_ACTION</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]; IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); boolean found= false; for (int j= 0; j < fFilterActions.length; j++) { int currProperty= fFilterActions[j].getFilterProperty(); if (currProperty == filterProperty) { fFilterActions[j].setChecked(set); found= true; break; } } if (found) { store.setValue(getPreferenceKey(filterProperty), hasMemberFilter(filterProperty)); if (set) { fFilter.addFilter(filterProperty); } else { fFilter.removeFilter(filterProperty); } } } if (refresh) { fViewer.getControl().setRedraw(false); BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() { public void run() { fViewer.refresh(); } }); fViewer.getControl().setRedraw(true); } } private boolean isSet(int flag, int set) { return (flag & set) != 0; } /** * 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>, <code>FILTER_PRIVATE</code> and <code>FILTER_LOCALTYPES</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))); memento.putString(TAG_HIDELOCALTYPES, String.valueOf(hasMemberFilter(FILTER_LOCALTYPES))); } /** * 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, FILTER_LOCALTYPES}, new boolean[] { Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)).booleanValue(), Boolean.valueOf(memento.getString(TAG_HIDESTATIC)).booleanValue(), Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)).booleanValue(), Boolean.valueOf(memento.getString(TAG_HIDELOCALTYPES)).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) { if (fInViewMenu) return; for (int i= 0; i < fFilterActions.length; i++) { tbm.add(fFilterActions[i]); } } /** * Adds the filter actions to the given menu manager. * * @param menu the menu manager to which the actions are added * @since 2.1 */ public void contributeToViewMenu(IMenuManager menu) { if (!fInViewMenu) return; final String filters= "filters"; //$NON-NLS-1$ if (menu.find(filters) != null) { for (int i= 0; i < fFilterActions.length; i++) { menu.prependToGroup(filters, fFilterActions[i]); } } else { for (int i= 0; i < fFilterActions.length; i++) { menu.add(fFilterActions[i]); } } } /* (non-Javadoc) * @see ActionGroup#dispose() */ public void dispose() { super.dispose(); } }
45,461
Bug 45461 NPE in JavaAnnotationIterator
I20031023 I noticed this in my log (not sure how I caused it) !ENTRY org.eclipse.ui 4 0 Oct 23, 2003 12:34:09.387 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator.<init> (JavaAnnotationIterator.java:44) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.getAnnotation (JavaEditor.java:2842) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.updateStatusLine (JavaEditor.java:2603) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor$EditorSelectionChangedListener .selectionChanged(JavaEditor.java:251) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor$EditorSelectionChangedListener .selectionChanged(JavaEditor.java:244) at org.eclipse.jface.text.TextViewer.firePostSelectionChanged (TextViewer.java:2142) at org.eclipse.jface.text.TextViewer.firePostSelectionChanged (TextViewer.java:2095) at org.eclipse.jface.text.TextViewer$4.run(TextViewer.java:2074) at org.eclipse.swt.widgets.Display.runTimer(Display.java:2215) at org.eclipse.swt.widgets.Display.messageProc(Display.java:1749) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1346) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1861) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1579) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1562) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:765) at org.eclipse.core.launcher.Main.main(Main.java:599)
resolved fixed
db50285
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T08:21:06Z
2003-10-23T17:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaAnnotationIterator.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.util.Iterator; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; /** * Filters problems based on their types. */ public class JavaAnnotationIterator implements Iterator { private Iterator fIterator; private Annotation fNext; private boolean fSkipIrrelevants; private boolean fReturnAllAnnotations; /** * Equivalent to <code>JavaAnnotationIterator(model, skipIrrelevants, false)</code>. */ public JavaAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants) { this(model, skipIrrelevants, false); } /** * Returns a new JavaAnnotationIterator. * @param model the annotation model * @param skipIrrelevants whether to skip irrelevant annotations * @param returnAllAnnotations Whether to return non IJavaAnnotations as well */ public JavaAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants, boolean returnAllAnnotations) { fReturnAllAnnotations= returnAllAnnotations; fIterator= model.getAnnotationIterator(); fSkipIrrelevants= skipIrrelevants; skip(); } private void skip() { while (fIterator.hasNext()) { Object next= fIterator.next(); if (next instanceof IJavaAnnotation) { IJavaAnnotation a= (IJavaAnnotation) next; if (fSkipIrrelevants) { if (a.isRelevant()) { fNext= (Annotation)a; return; } } else { fNext= (Annotation)a; return; } } else if (fReturnAllAnnotations) { fNext= (Annotation)next; return; } } fNext= null; } /* * @see Iterator#hasNext() */ public boolean hasNext() { return fNext != null; } /* * @see Iterator#next() */ public Object next() { try { return fNext; } finally { skip(); } } /* * @see Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } }
45,491
Bug 45491 Wrong dependency between compiler javadoc options
The boolean option 'Missing javadoc tags in public types, methods and fields' is not disabled when the "master" javadoc option 'Problem in Javadoc tags' is set to 'Ignore'. Correct behavior should be indentical for example to compiler option: 'Local variable declaration hides another fields or variables' and its dependent option: 'Include constructor or setter method parameters'
resolved fixed
fc2a332
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T13:20:06Z
2003-10-24T10:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerConfigurationBlock.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; /** */ public class CompilerConfigurationBlock extends OptionsConfigurationBlock { // Preference store keys, see JavaCore.getOptions private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR; private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR; private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR; private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL; private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; //private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE; //private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT; private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD; private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME; private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION; private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK; private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL; private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER; private static final String PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE; private static final String PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT; private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION; private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL; private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER; private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT; private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT; private static final String PREF_PB_UNUSED_PRIVATE= JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER; private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER; private static final String PREF_PB_NO_EFFECT_ASSIGNMENT= JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT; private static final String PREF_PB_CHAR_ARRAY_IN_CONCAT= JavaCore.COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION; private static final String PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT= JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT; private static final String PREF_PB_LOCAL_VARIABLE_HIDING= JavaCore.COMPILER_PB_LOCAL_VARIABLE_HIDING; private static final String PREF_PB_FIELD_HIDING= JavaCore.COMPILER_PB_FIELD_HIDING; private static final String PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD= JavaCore.COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD; private static final String PREF_PB_INDIRECT_STATIC_ACCESS= JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS; private static final String PREF_PB_SUPERFLUOUS_SEMICOLON= JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON; private static final String PREF_PB_UNNECESSARY_TYPE_CHECK= JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK; private static final String PREF_PB_INVALID_ANNOTATION= JavaCore.COMPILER_PB_INVALID_ANNOTATION; private static final String PREF_PB_MISSING_ANNOTATION= "org.eclipse.jdt.core.compiler.problem.missingAnnotation"; //$NON-NLS-1$ private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE; private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE; private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER; private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH; private static final String PREF_BUILD_CLEAN_OUTPUT_FOLDER= JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER; private static final String PREF_ENABLE_EXCLUSION_PATTERNS= JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS; private static final String PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS= JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS; private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH; private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH; private static final String PREF_PB_INCOMPATIBLE_JDK_LEVEL= JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL; private static final String PREF_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE; private static final String PREF_PB_DUPLICATE_RESOURCE= JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE; private static final String PREF_PB_INCOMPATIBLE_INTERFACE_METHOD= JavaCore.COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD; private static final String PREF_PB_UNDOCUMENTED_EMPTY_BLOCK= JavaCore.COMPILER_PB_UNDOCUMENTED_EMPTY_BLOCK; private static final String PREF_PB_FINALLY_BLOCK_NOT_COMPLETING= JavaCore.COMPILER_PB_FINALLY_BLOCK_NOT_COMPLETING; private static final String PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION= JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION; private static final String PREF_PB_UNQUALIFIED_FIELD_ACCESS= JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS; private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$ // values private static final String GENERATE= JavaCore.GENERATE; private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE; private static final String PRESERVE= JavaCore.PRESERVE; private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT; private static final String VERSION_1_1= JavaCore.VERSION_1_1; private static final String VERSION_1_2= JavaCore.VERSION_1_2; private static final String VERSION_1_3= JavaCore.VERSION_1_3; private static final String VERSION_1_4= JavaCore.VERSION_1_4; private static final String ERROR= JavaCore.ERROR; private static final String WARNING= JavaCore.WARNING; private static final String IGNORE= JavaCore.IGNORE; private static final String ABORT= JavaCore.ABORT; private static final String CLEAN= JavaCore.CLEAN; private static final String ENABLED= JavaCore.ENABLED; private static final String DISABLED= JavaCore.DISABLED; private static final String DEFAULT= "default"; //$NON-NLS-1$ private static final String USER= "user"; //$NON-NLS-1$ private ArrayList fComplianceControls; private PixelConverter fPixelConverter; private IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus; public CompilerConfigurationBlock(IStatusChangeListener context, IJavaProject project) { super(context, project); fComplianceControls= new ArrayList(); fComplianceStatus= new StatusInfo(); fMaxNumberProblemsStatus= new StatusInfo(); fResourceFilterStatus= new StatusInfo(); } private final String[] KEYS= new String[] { PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL, PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL, PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS, PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_UNUSED_IMPORT, PREF_PB_MAX_PER_UNIT, PREF_SOURCE_COMPATIBILITY, PREF_COMPLIANCE, PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH, PREF_PB_CIRCULAR_BUILDPATH, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_BUILD_CLEAN_OUTPUT_FOLDER, PREF_PB_DUPLICATE_RESOURCE, PREF_PB_NO_EFFECT_ASSIGNMENT, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, PREF_PB_UNUSED_PRIVATE, PREF_PB_CHAR_ARRAY_IN_CONCAT, PREF_ENABLE_EXCLUSION_PATTERNS, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, PREF_PB_LOCAL_VARIABLE_HIDING, PREF_PB_FIELD_HIDING, PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, PREF_PB_INCOMPATIBLE_JDK_LEVEL, PREF_PB_INDIRECT_STATIC_ACCESS, PREF_PB_SUPERFLUOUS_SEMICOLON, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, PREF_PB_UNNECESSARY_TYPE_CHECK, PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, PREF_PB_UNQUALIFIED_FIELD_ACCESS, PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, PREF_PB_INVALID_ANNOTATION, PREF_PB_MISSING_ANNOTATION }; protected String[] getAllKeys() { return KEYS; } protected final Map getOptions(boolean inheritJavaCoreOptions) { Map map= super.getOptions(inheritJavaCoreOptions); map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map)); return map; } protected final Map getDefaultOptions() { Map map= super.getDefaultOptions(); map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map)); return map; } /* * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { fPixelConverter= new PixelConverter(parent); setShell(parent.getShell()); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); Composite commonComposite= createStyleTabContent(folder); Composite unusedComposite= createUnusedCodeTabContent(folder); Composite advancedComposite= createAdvancedTabContent(folder); Composite complianceComposite= createComplianceTabContent(folder); Composite othersComposite= createBuildPathTabContent(folder); TabItem item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.tabtitle")); //$NON-NLS-1$ item.setControl(commonComposite); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.tabtitle")); //$NON-NLS-1$ item.setControl(advancedComposite); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.tabtitle")); //$NON-NLS-1$ item.setControl(unusedComposite); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); //$NON-NLS-1$ item.setControl(complianceComposite); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.others.tabtitle")); //$NON-NLS-1$ item.setControl(othersComposite); validateSettings(null, null); return folder; } private Composite createStyleTabContent(Composite folder) { String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ }; String[] enabledDisabled= new String[] { ENABLED, DISABLED }; int nColumns= 3; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; Composite composite= new Composite(folder, SWT.NULL); composite.setLayout(layout); Label description= new Label(composite, SWT.WRAP); description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.description")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= nColumns; gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50); description.setLayoutData(gd); String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_no_effect_assignment.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_NO_EFFECT_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_indirect_access_to_static.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_INDIRECT_STATIC_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_accidential_assignement.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_finally_block_not_completing.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_undocumented_empty_block.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_invalid_javadoc.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_INVALID_ANNOTATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); int indent= fPixelConverter.convertWidthInCharsToPixels(2); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_javadoc.label"); //$NON-NLS-1$ addCheckBox(composite, label, PREF_PB_MISSING_ANNOTATION, enabledDisabled, indent); return composite; } private Composite createAdvancedTabContent(TabFolder folder) { String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ }; String[] enabledDisabled= new String[] { ENABLED, DISABLED }; int nColumns= 3; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; Composite composite= new Composite(folder, SWT.NULL); composite.setLayout(layout); Label description= new Label(composite, SWT.WRAP); description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.description")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= nColumns; gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50); description.setLayoutData(gd); String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_local_variable_hiding.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_LOCAL_VARIABLE_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0); int indent= fPixelConverter.convertWidthInCharsToPixels(2); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_special_param_hiding.label"); //$NON-NLS-1$ addCheckBox(composite, label, PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, enabledDisabled, indent); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_field_hiding.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_FIELD_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incompatible_interface_method.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_char_array_in_concat.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_CHAR_ARRAY_IN_CONCAT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unqualified_field_access.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_UNQUALIFIED_FIELD_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, 0); gd= new GridData(); gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(6); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$ Text text= addTextField(composite, label, PREF_PB_MAX_PER_UNIT, 0, 0); text.setTextLimit(6); text.setLayoutData(gd); return composite; } private Composite createUnusedCodeTabContent(TabFolder folder) { String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ }; String[] enabledDisabled= new String[] { ENABLED, DISABLED }; int nColumns= 3; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; Composite composite= new Composite(folder, SWT.NULL); composite.setLayout(layout); Label description= new Label(composite, SWT.WRAP); description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.description")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= nColumns; gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50); description.setLayoutData(gd); Composite combos= composite; String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_local.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_parameter.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0); int indent= fPixelConverter.convertWidthInCharsToPixels(2); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_signal_param_in_overriding.label"); //$NON-NLS-1$ addCheckBox(combos, label, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, enabledDisabled, indent); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_signal_param_in_abstract.label"); //$NON-NLS-1$ addCheckBox(combos, label, PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, enabledDisabled, indent); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_imports.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_private.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_UNUSED_PRIVATE, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$ addCheckBox(composite, label, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, indent); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_superfluous_semicolon.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_SUPERFLUOUS_SEMICOLON, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unnecessary_type_check.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_UNNECESSARY_TYPE_CHECK, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_throwing_exception.label"); //$NON-NLS-1$ addComboBox(composite, label, PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, errorWarningIgnore, errorWarningIgnoreLabels, 0); return composite; } private Composite createBuildPathTabContent(TabFolder folder) { String[] abortIgnoreValues= new String[] { ABORT, IGNORE }; String[] cleanIgnoreValues= new String[] { CLEAN, IGNORE }; String[] enableDisableValues= new String[] { ENABLED, DISABLED }; String[] errorWarning= new String[] { ERROR, WARNING }; String[] errorWarningLabels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.warning") //$NON-NLS-1$ }; int nColumns= 3; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; Composite othersComposite= new Composite(folder, SWT.NULL); othersComposite.setLayout(layout); Label description= new Label(othersComposite, SWT.WRAP); description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.build_warnings.description")); //$NON-NLS-1$ GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= nColumns; description.setLayoutData(gd); String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incomplete_build_path.label"); //$NON-NLS-1$ addComboBox(othersComposite, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_build_path_cycles.label"); //$NON-NLS-1$ addComboBox(othersComposite, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_duplicate_resources.label"); //$NON-NLS-1$ addComboBox(othersComposite, label, PREF_PB_DUPLICATE_RESOURCE, errorWarning, errorWarningLabels, 0); String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ }; label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_check_prereq_binary_level.label"); //$NON-NLS-1$ addComboBox(othersComposite, label, PREF_PB_INCOMPATIBLE_JDK_LEVEL, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.build_invalid_classpath.label"); //$NON-NLS-1$ addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.build_clean_outputfolder.label"); //$NON-NLS-1$ addCheckBox(othersComposite, label, PREF_BUILD_CLEAN_OUTPUT_FOLDER, cleanIgnoreValues, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.enable_exclusion_patterns.label"); //$NON-NLS-1$ addCheckBox(othersComposite, label, PREF_ENABLE_EXCLUSION_PATTERNS, enableDisableValues, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.enable_multiple_outputlocations.label"); //$NON-NLS-1$ addCheckBox(othersComposite, label, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, enableDisableValues, 0); description= new Label(othersComposite, SWT.WRAP); description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.description")); //$NON-NLS-1$ gd= new GridData(GridData.FILL); gd.horizontalSpan= nColumns; gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60); description.setLayoutData(gd); label= PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.label"); //$NON-NLS-1$ Text text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER, 0, 0); gd= (GridData) text.getLayoutData(); gd.grabExcessHorizontalSpace= true; gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(10); return othersComposite; } private Composite createComplianceTabContent(Composite folder) { GridLayout layout= new GridLayout(); layout.numColumns= 1; String[] values34= new String[] { VERSION_1_3, VERSION_1_4 }; String[] values34Labels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$ }; Composite compComposite= new Composite(folder, SWT.NULL); compComposite.setLayout(layout); int nColumns= 3; layout= new GridLayout(); layout.numColumns= nColumns; Group group= new Group(compComposite, SWT.NONE); group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.group.label")); //$NON-NLS-1$ group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); String label= PreferencesMessages.getString("CompilerConfigurationBlock.compiler_compliance.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_COMPLIANCE, values34, values34Labels, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.default_settings.label"); //$NON-NLS-1$ addCheckBox(group, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0); int indent= fPixelConverter.convertWidthInCharsToPixels(2); Control[] otherChildren= group.getChildren(); String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 }; String[] values14Labels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.version11"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.version12"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$ }; label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_targetplatform.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent); label= PreferencesMessages.getString("CompilerConfigurationBlock.source_compatibility.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent); String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ }; label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_assert_as_identifier.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent); Control[] allChildren= group.getChildren(); fComplianceControls.addAll(Arrays.asList(allChildren)); fComplianceControls.removeAll(Arrays.asList(otherChildren)); layout= new GridLayout(); layout.numColumns= nColumns; group= new Group(compComposite, SWT.NONE); group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.classfiles.group.label")); //$NON-NLS-1$ group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE }; label= PreferencesMessages.getString("CompilerConfigurationBlock.variable_attr.label"); //$NON-NLS-1$ addCheckBox(group, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.line_number_attr.label"); //$NON-NLS-1$ addCheckBox(group, label, PREF_LINE_NUMBER_ATTR, generateValues, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.source_file_attr.label"); //$NON-NLS-1$ addCheckBox(group, label, PREF_SOURCE_FILE_ATTR, generateValues, 0); label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_unused_local.label"); //$NON-NLS-1$ addCheckBox(group, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0); return compComposite; } /* (non-javadoc) * Update fields and validate. * @param changedKey Key that changed, or null, if all changed. */ protected void validateSettings(String changedKey, String newValue) { if (changedKey != null) { if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) { updateComplianceEnableState(); if (DEFAULT.equals(newValue)) { updateComplianceDefaultSettings(); } fComplianceStatus= validateCompliance(); } else if (PREF_COMPLIANCE.equals(changedKey)) { if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT)) { updateComplianceDefaultSettings(); } fComplianceStatus= validateCompliance(); } else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) || PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) || PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) { fComplianceStatus= validateCompliance(); } else if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) { fMaxNumberProblemsStatus= validateMaxNumberProblems(); } else if (PREF_RESOURCE_FILTER.equals(changedKey)) { fResourceFilterStatus= validateResourceFilters(); } else if (PREF_PB_UNUSED_PARAMETER.equals(changedKey) || PREF_PB_DEPRECATION.equals(changedKey) || PREF_PB_LOCAL_VARIABLE_HIDING.equals(changedKey)) { updateEnableStates(); } else { return; } } else { updateEnableStates(); updateComplianceEnableState(); fComplianceStatus= validateCompliance(); fMaxNumberProblemsStatus= validateMaxNumberProblems(); fResourceFilterStatus= validateResourceFilters(); } IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus }); fContext.statusChanged(status); } private void updateEnableStates() { boolean enableUnusedParams= !checkValue(PREF_PB_UNUSED_PARAMETER, IGNORE); getCheckBox(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING).setEnabled(enableUnusedParams); getCheckBox(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT).setEnabled(enableUnusedParams); boolean enableDeprecation= !checkValue(PREF_PB_DEPRECATION, IGNORE); getCheckBox(PREF_PB_DEPRECATION_IN_DEPRECATED_CODE).setEnabled(enableDeprecation); boolean enableHiding= !checkValue(PREF_PB_LOCAL_VARIABLE_HIDING, IGNORE); getCheckBox(PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD).setEnabled(enableHiding); } private IStatus validateCompliance() { StatusInfo status= new StatusInfo(); if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) { if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); //$NON-NLS-1$ return status; } else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13trg14.error")); //$NON-NLS-1$ return status; } } if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) { status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14asrterr.error")); //$NON-NLS-1$ return status; } } if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14tgt14.error")); //$NON-NLS-1$ return status; } } return status; } private IStatus validateMaxNumberProblems() { String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT); StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value <= 0) { status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$ } } catch (NumberFormatException e) { status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$ } } return status; } private IStatus validateResourceFilters() { String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER); IWorkspace workspace= ResourcesPlugin.getWorkspace(); String[] filters= getTokens(text, ","); //$NON-NLS-1$ for (int i= 0; i < filters.length; i++) { String fileName= filters[i].replace('*', 'x'); int resourceType= IResource.FILE; int lastCharacter= fileName.length() - 1; if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') { fileName= fileName.substring(0, lastCharacter); resourceType= IResource.FOLDER; } IStatus status= workspace.validateName(fileName, resourceType); if (status.matches(IStatus.ERROR)) { String message= PreferencesMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$ return new StatusInfo(IStatus.ERROR, message); } } return new StatusInfo(); } /* * Update the compliance controls' enable state */ private void updateComplianceEnableState() { boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER); for (int i= fComplianceControls.size() - 1; i >= 0; i--) { Control curr= (Control) fComplianceControls.get(i); curr.setEnabled(enabled); } } /* * Set the default compliance values derived from the chosen level */ private void updateComplianceDefaultSettings() { Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE); if (VERSION_1_3.equals(complianceLevel)) { fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE); fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3); fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1); } else if (VERSION_1_4.equals(complianceLevel)) { fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, WARNING); fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3); fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_2); } updateControls(); } /* * Evaluate if the current compliance setting correspond to a default setting */ private static String getCurrentCompliance(Map map) { Object complianceLevel= map.get(PREF_COMPLIANCE); if ((VERSION_1_3.equals(complianceLevel) && IGNORE.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER)) && VERSION_1_3.equals(map.get(PREF_SOURCE_COMPATIBILITY)) && VERSION_1_1.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM))) || (VERSION_1_4.equals(complianceLevel) && WARNING.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER)) && VERSION_1_3.equals(map.get(PREF_SOURCE_COMPATIBILITY)) && VERSION_1_2.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM)))) { return DEFAULT; } return USER; } protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { String title= PreferencesMessages.getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$ String message; if (workspaceSettings) { message= PreferencesMessages.getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$ } else { message= PreferencesMessages.getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$ } return new String[] { title, message }; } }
44,426
Bug 44426 Move member to top level: Wrong constructor [refactoring]
20031008 - Create the following CU - select the member type in the outliner, choose: 'Move member type to new file' - The code is changed to use a constructor with 'this', howvere, the created type does not have this constructor public class A { class Vector { } public void foo() { Vector v= new Vector(); } } --- -> Vector v= new Vector(this); -- class Vector { /** * */ Vector() { // TODO Auto-generated constructor stub } }
resolved fixed
e6833d4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T15:19:04Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/testFail_nonstatic_0/in/A.java
package p; class A{ class Inner{ int a; } }
44,426
Bug 44426 Move member to top level: Wrong constructor [refactoring]
20031008 - Create the following CU - select the member type in the outliner, choose: 'Move member type to new file' - The code is changed to use a constructor with 'this', howvere, the created type does not have this constructor public class A { class Vector { } public void foo() { Vector v= new Vector(); } } --- -> Vector v= new Vector(this); -- class Vector { /** * */ Vector() { // TODO Auto-generated constructor stub } }
resolved fixed
e6833d4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T15:19:04Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test_nonstatic_38/out/Inner.java
package p; class Inner { /** * */ Inner() { // TODO Auto-generated constructor stub } public void doit() { } }
44,426
Bug 44426 Move member to top level: Wrong constructor [refactoring]
20031008 - Create the following CU - select the member type in the outliner, choose: 'Move member type to new file' - The code is changed to use a constructor with 'this', howvere, the created type does not have this constructor public class A { class Vector { } public void foo() { Vector v= new Vector(); } } --- -> Vector v= new Vector(this); -- class Vector { /** * */ Vector() { // TODO Auto-generated constructor stub } }
resolved fixed
e6833d4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T15:19:04Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test_nonstatic_39/out/Inner.java
package p; import p.A.Stat; class Inner { /** * */ Inner() { // TODO Auto-generated constructor stub } public void doit() { A.foo(); A.fred++; new Stat(); } }
44,426
Bug 44426 Move member to top level: Wrong constructor [refactoring]
20031008 - Create the following CU - select the member type in the outliner, choose: 'Move member type to new file' - The code is changed to use a constructor with 'this', howvere, the created type does not have this constructor public class A { class Vector { } public void foo() { Vector v= new Vector(); } } --- -> Vector v= new Vector(this); -- class Vector { /** * */ Vector() { // TODO Auto-generated constructor stub } }
resolved fixed
e6833d4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T15:19:04Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui/core
44,426
Bug 44426 Move member to top level: Wrong constructor [refactoring]
20031008 - Create the following CU - select the member type in the outliner, choose: 'Move member type to new file' - The code is changed to use a constructor with 'this', howvere, the created type does not have this constructor public class A { class Vector { } public void foo() { Vector v= new Vector(); } } --- -> Vector v= new Vector(this); -- class Vector { /** * */ Vector() { // TODO Auto-generated constructor stub } }
resolved fixed
e6833d4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T15:19:04Z
2003-10-08T13:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java
44,429
Bug 44429 Move member to top level: Description strange
20031008 The 'Move Member to New File' refactoring dialog allows you to specify the name of the field that is created. I think the label in the dialog is complicated: ' Entre name for enclosing instance'. I can rename the enclosing instance? Why not simply write: 'Field name:' The labels above already say that this is new field created to refer to the enclosing instance.
resolved fixed
f8b41f5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T15:25:39Z
2003-10-08T13:33:20Z
org.eclipse.jdt.ui/ui
44,429
Bug 44429 Move member to top level: Description strange
20031008 The 'Move Member to New File' refactoring dialog allows you to specify the name of the field that is created. I think the label in the dialog is complicated: ' Entre name for enclosing instance'. I can rename the enclosing instance? Why not simply write: 'Field name:' The labels above already say that this is new field created to refer to the enclosing instance.
resolved fixed
f8b41f5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-24T15:25:39Z
2003-10-08T13:33:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveInnerToTopWizard.java
45,509
Bug 45509 Allow to disable icons in vertical ruler
I20031023 A feature for Dirk
resolved fixed
a09f2be
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-27T15:26:24Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; 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.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; 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.source.SourceViewer; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; /* * The page for setting the editor options. */ public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX; private static final String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; private static final String DELIMITER= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ public final OverlayPreferenceStore.OverlayKey[] fKeys; private final String[][] fSyntaxColorListModel= new String[][] { { PreferencesMessages.getString("JavaEditorPreferencePage.multiLineComment"), PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.singleLineComment"), PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.strings"), PreferenceConstants.EDITOR_STRING_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.methodNames"), PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.operators"), PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaCommentTaskTags"), PreferenceConstants.EDITOR_TASK_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocLinks"), PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ }; private final String[][] fAppearanceColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColor2"), ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.findScopeColor2"), PreferenceConstants.EDITOR_FIND_SCOPE_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkedPositionColor2"), PreferenceConstants.EDITOR_LINKED_POSITION_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR}, //$NON-NLS-1$ }; private final String[][] fAnnotationColorListModel; private final String[][] fContentAssistColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND } //$NON-NLS-1$ }; private OverlayPreferenceStore fOverlayStore; private JavaTextTools fJavaTextTools; private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; private Map fColorButtons= new HashMap(); private Map fCheckBoxes= new HashMap(); private SelectionListener fCheckBoxListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { Button button= (Button) e.widget; fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); } }; private Map fTextFields= new HashMap(); private ModifyListener fTextFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { Text text= (Text) e.widget; fOverlayStore.setValue((String) fTextFields.get(text), text.getText()); } }; private ArrayList fNumberFields= new ArrayList(); private ModifyListener fNumberFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { numberFieldChanged((Text) e.widget); } }; private List fSyntaxColorList; private List fAppearanceColorList; private List fContentAssistColorList; private List fAnnotationList; private ColorEditor fSyntaxForegroundColorEditor; private ColorEditor fAppearanceColorEditor; private ColorEditor fAnnotationForegroundColorEditor; private ColorEditor fContentAssistColorEditor; private ColorEditor fBackgroundColorEditor; private Button fBackgroundDefaultRadioButton; private Button fBackgroundCustomRadioButton; private Button fBackgroundColorButton; private Button fBoldCheckBox; private Button fAddJavaDocTagsButton; private Button fEscapeStringsButton; private Button fGuessMethodArgumentsButton; private SourceViewer fPreviewViewer; private Color fBackgroundColor; private Control fAutoInsertDelayText; private Control fAutoInsertJavaTriggerText; private Control fAutoInsertJavaDocTriggerText; private Label fAutoInsertDelayLabel; private Label fAutoInsertJavaTriggerLabel; private Label fAutoInsertJavaDocTriggerLabel; private Button fShowInTextCheckBox; private Button fHighlightInTextCheckBox; private Button fShowInOverviewRulerCheckBox; private Text fBrowserLikeLinksKeyModifierText; private Button fBrowserLikeLinksCheckBox; private StatusInfo fBrowserLikeLinksKeyModifierStatus; private Button fCompletionInsertsRadioButton; private Button fCompletionOverwritesRadioButton; public JavaEditorPreferencePage() { setDescription(PreferencesMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); MarkerAnnotationPreferences markerAnnotationPreferences= new MarkerAnnotationPreferences(); fKeys= createOverlayStoreKeys(markerAnnotationPreferences); fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys); fAnnotationColorListModel= createAnnotationTypeListModel(markerAnnotationPreferences); } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys(MarkerAnnotationPreferences preferences) { ArrayList overlayKeys= new ArrayList(); Iterator e= preferences.getAnnotationPreferences().iterator(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOREGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BACKGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.EDITOR_TAB_WIDTH)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_STRING_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STRING_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TASK_TAG_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_TAG_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MATCHING_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINK_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CORRECTION_INDICATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SPACES_FOR_TABS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOACTIVATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOINSERT)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ADDIMPORT)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ESCAPE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); // overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FORMAT_JAVADOCS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_HOME_END)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMAT)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMATHTML)); while (e.hasNext()) { AnnotationPreference info= (AnnotationPreference) e.next(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, info.getColorPreferenceKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getTextPreferenceKey())); if (info.getHighlightPreferenceKey() != null) overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getHighlightPreferenceKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getOverviewRulerPreferenceKey())); } OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; overlayKeys.toArray(keys); return keys; } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); } private void handleSyntaxColorListSelection() { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fSyntaxForegroundColorEditor.setColorValue(rgb); fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); } private void handleAppearanceColorListSelection() { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAppearanceColorEditor.setColorValue(rgb); } private void handleContentAssistColorListSelection() { int i= fContentAssistColorList.getSelectionIndex(); String key= fContentAssistColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fContentAssistColorEditor.setColorValue(rgb); } private void handleAnnotationListSelection() { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAnnotationForegroundColorEditor.setColorValue(rgb); key= fAnnotationColorListModel[i][2]; fShowInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); key= fAnnotationColorListModel[i][3]; fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); key= fAnnotationColorListModel[i][4]; if (key != null) { fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); fHighlightInTextCheckBox.setEnabled(true); } else fHighlightInTextCheckBox.setEnabled(false); } private Control createSyntaxPage(Composite parent) { Composite colorComposite= new Composite(parent, SWT.NULL); colorComposite.setLayout(new GridLayout()); Group backgroundComposite= new Group(colorComposite, SWT.SHADOW_ETCHED_IN); backgroundComposite.setLayout(new RowLayout()); backgroundComposite.setText(PreferencesMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ SelectionListener backgroundSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean custom= fBackgroundCustomRadioButton.getSelection(); fBackgroundColorButton.setEnabled(custom); fOverlayStore.setValue(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, !custom); } public void widgetDefaultSelected(SelectionEvent e) {} }; fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundDefaultRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundCustomRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundColorEditor= new ColorEditor(backgroundComposite); fBackgroundColorButton= fBackgroundColorEditor.getButton(); Label label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite editorComposite= new Composite(colorComposite, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); editorComposite.setLayoutData(gd); fSyntaxColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fSyntaxColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); label= new Label(stylesComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fSyntaxForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fBoldCheckBox= new Button(stylesComposite, SWT.CHECK); fBoldCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fBoldCheckBox.setLayoutData(gd); label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control previewer= createPreviewer(colorComposite); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(20); gd.heightHint= convertHeightInCharsToPixels(5); previewer.setLayoutData(gd); fSyntaxColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleSyntaxColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fSyntaxForegroundColorEditor.getColorValue()); } }); fBackgroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { PreferenceConverter.setValue(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, fBackgroundColorEditor.getColorValue()); } }); fBoldCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; fOverlayStore.setValue(key + BOLD, fBoldCheckBox.getSelection()); } }); return colorComposite; } private Control createPreviewer(Composite parent) { Preferences coreStore= createTemporaryCorePreferenceStore(); fJavaTextTools= new JavaTextTools(fOverlayStore, coreStore, false); fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); fPreviewViewer.configure(new JavaSourceViewerConfiguration(fJavaTextTools, null, IJavaPartitions.JAVA_PARTITIONING)); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); fPreviewViewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(fPreviewViewer, fJavaTextTools); fPreviewViewer.setEditable(false); String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ IDocument document= new Document(content); fJavaTextTools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING); fPreviewViewer.setDocument(document); return fPreviewViewer.getControl(); } private Preferences createTemporaryCorePreferenceStore() { Preferences result= new Preferences(); result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$ return result; } private Control createAppearancePage(Composite parent) { Composite appearanceComposite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; appearanceComposite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ addTextField(appearanceComposite, label, PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ addTextField(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, 0); Label l= new Label(appearanceComposite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(appearanceComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(appearanceComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fAppearanceColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fAppearanceColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fAppearanceColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fAppearanceColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAppearanceColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue()); } }); return appearanceComposite; } private Control createAnnotationsPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String text= PreferencesMessages.getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$ addCheckBox(composite, text, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); text= PreferencesMessages.getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ addCheckBox(composite, text, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); addFiller(composite); Label label= new Label(composite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationPresentationOptions")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; label.setLayoutData(gd); Composite editorComposite= new Composite(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAnnotationList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(10); fAnnotationList.setLayoutData(gd); Composite optionsComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; optionsComposite.setLayout(layout); optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); fShowInTextCheckBox= new Button(optionsComposite, SWT.CHECK); fShowInTextCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInText")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fShowInTextCheckBox.setLayoutData(gd); fHighlightInTextCheckBox= new Button(optionsComposite, SWT.CHECK); fHighlightInTextCheckBox.setText(PreferencesMessages.getString("TextEditorPreferencePage.annotations.highlightInText")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fHighlightInTextCheckBox.setLayoutData(gd); fShowInOverviewRulerCheckBox= new Button(optionsComposite, SWT.CHECK); fShowInOverviewRulerCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fShowInOverviewRulerCheckBox.setLayoutData(gd); label= new Label(optionsComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fAnnotationForegroundColorEditor= new ColorEditor(optionsComposite); Button foregroundColorButton= fAnnotationForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fAnnotationList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAnnotationListSelection(); } }); fShowInTextCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][2]; fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection()); } }); fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][4]; fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection()); } }); fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][3]; fOverlayStore.setValue(key, fShowInOverviewRulerCheckBox.getSelection()); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAnnotationForegroundColorEditor.getColorValue()); } }); return composite; } private String[][] createAnnotationTypeListModel(MarkerAnnotationPreferences preferences) { ArrayList listModelItems= new ArrayList(); Iterator e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { AnnotationPreference info= (AnnotationPreference) e.next(); listModelItems.add(new String[] { info.getPreferenceLabel(), info.getColorPreferenceKey(), info.getTextPreferenceKey(), info.getOverviewRulerPreferenceKey(), info.getHighlightPreferenceKey()}); } String[][] items= new String[listModelItems.size()][]; listModelItems.toArray(items); return items; } private Control createTypingPage(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 1; composite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.subWordNavigation"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); addFiller(composite); Group group= new Group(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; group.setLayout(layout); group.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ label= PreferencesMessages.getString("JavaEditorPreferencePage.wrapStrings"); //$NON-NLS-1$ Button button= addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.escapeStrings"); //$NON-NLS-1$ fEscapeStringsButton= addCheckBox(group, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS, 1); createDependency(button, fEscapeStringsButton); label= PreferencesMessages.getString("JavaEditorPreferencePage.smartPaste"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeStrings"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBrackets"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBraces"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); //$NON-NLS-1$ button= addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.addJavaDocTags"); //$NON-NLS-1$ fAddJavaDocTagsButton= addCheckBox(group, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); createDependency(button, fAddJavaDocTagsButton); // label= PreferencesMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); //$NON-NLS-1$ // addCheckBox(group, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); return composite; } private void addFiller(Composite composite) { Label filler= new Label(composite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; filler.setLayoutData(gd); } private static void indent(Control control) { GridData gridData= new GridData(); gridData.horizontalIndent= 20; control.setLayoutData(gridData); } private static void createDependency(final Button master, final Control slave) { indent(slave); master.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) {} }); } private Control createContentAssistPage(Composite parent) { Composite contentAssistComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; contentAssistComposite.setLayout(layout); addCompletionRadioButtons(contentAssistComposite); String label; label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOINSERT, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ADDIMPORT, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ Button button= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ fGuessMethodArgumentsButton= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0); createDependency(button, fGuessMethodArgumentsButton); label= PreferencesMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$ final Button autoactivation= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION, 0); autoactivation.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { updateAutoactivationControls(); } }); Control[] labelledTextField; label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$ labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 4, 0, true); fAutoInsertDelayLabel= getLabelControl(labelledTextField); fAutoInsertDelayText= getTextControl(labelledTextField); label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$ labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, 4, 0, false); fAutoInsertJavaTriggerLabel= getLabelControl(labelledTextField); fAutoInsertJavaTriggerText= getTextControl(labelledTextField); label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$ labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, 4, 0, false); fAutoInsertJavaDocTriggerLabel= getLabelControl(labelledTextField); fAutoInsertJavaDocTriggerText= getTextControl(labelledTextField); Label l= new Label(contentAssistComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.colorOptions")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(contentAssistComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fContentAssistColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fContentAssistColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fContentAssistColorEditor= new ColorEditor(stylesComposite); Button colorButton= fContentAssistColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; colorButton.setLayoutData(gd); fContentAssistColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleContentAssistColorListSelection(); } }); colorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fContentAssistColorList.getSelectionIndex(); String key= fContentAssistColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fContentAssistColorEditor.getColorValue()); } }); return contentAssistComposite; } private void addCompletionRadioButtons(Composite contentAssistComposite) { Composite completionComposite= new Composite(contentAssistComposite, SWT.NONE); GridData ccgd= new GridData(); ccgd.horizontalSpan= 2; completionComposite.setLayoutData(ccgd); GridLayout ccgl= new GridLayout(); ccgl.marginWidth= 0; ccgl.numColumns= 2; completionComposite.setLayout(ccgl); SelectionListener completionSelectionListener= new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { boolean insert= fCompletionInsertsRadioButton.getSelection(); fOverlayStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, insert); } }; fCompletionInsertsRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT); fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); //$NON-NLS-1$ fCompletionInsertsRadioButton.setLayoutData(new GridData()); fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); fCompletionOverwritesRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT); fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); //$NON-NLS-1$ fCompletionOverwritesRadioButton.setLayoutData(new GridData()); fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); } private Control createNavigationPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String text= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); //$NON-NLS-1$ fBrowserLikeLinksCheckBox= addCheckBox(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean state= fBrowserLikeLinksCheckBox.getSelection(); fBrowserLikeLinksKeyModifierText.setEnabled(state); handleBrowserLikeLinksKeyModifierModified(); } public void widgetDefaultSelected(SelectionEvent e) { } }); // Text field for modifier string text= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); //$NON-NLS-1$ fBrowserLikeLinksKeyModifierText= addTextField(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, 0, false); fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); if (computeStateMask(fOverlayStore.getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { // Fix possible illegal modifier string int stateMask= fOverlayStore.getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); if (stateMask == -1) fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierText.setText(EditorUtility.getModifierString(stateMask)); } fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { private boolean isModifierCandidate; public void keyPressed(KeyEvent e) { isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0; } public void keyReleased(KeyEvent e) { if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { String modifierString= fBrowserLikeLinksKeyModifierText.getText(); Point selection= fBrowserLikeLinksKeyModifierText.getSelection(); int i= selection.x - 1; while (i > -1 && Character.isWhitespace(modifierString.charAt(i))) { i--; } boolean needsPrefixDelimiter= i > -1 && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); i= selection.y; while (i < modifierString.length() && Character.isWhitespace(modifierString.charAt(i))) { i++; } boolean needsPostfixDelimiter= i < modifierString.length() && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); String insertString; if (needsPrefixDelimiter && needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPrefixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else insertString= Action.findModifierString(e.stateMask); fBrowserLikeLinksKeyModifierText.insert(insertString); } } }); fBrowserLikeLinksKeyModifierText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleBrowserLikeLinksKeyModifierModified(); } }); return composite; } private void handleBrowserLikeLinksKeyModifierModified() { String modifiers= fBrowserLikeLinksKeyModifierText.getText(); int stateMask= computeStateMask(modifiers); if (fBrowserLikeLinksCheckBox.getSelection() && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { if (stateMask == -1) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); //$NON-NLS-1$ setValid(false); StatusUtil.applyToStatusLine(this, fBrowserLikeLinksKeyModifierStatus); } else { fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); updateStatus(fBrowserLikeLinksKeyModifierStatus); } } private IStatus getBrowserLikeLinksKeyModifierStatus() { if (fBrowserLikeLinksKeyModifierStatus == null) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); return fBrowserLikeLinksKeyModifierStatus; } /** * Computes the state mask for the given modifier string. * * @param modifiers the string with the modifiers, separated by '+', '-', ';', ',' or '.' * @return the state mask or -1 if the input is invalid */ private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDefaultColors(); fOverlayStore.load(); fOverlayStore.start(); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); TabItem item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ item.setControl(createAppearancePage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ item.setControl(createSyntaxPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist")); //$NON-NLS-1$ item.setControl(createContentAssistPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationsTab.title")); //$NON-NLS-1$ item.setControl(createAnnotationsPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle")); //$NON-NLS-1$ item.setControl(createTypingPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.hoverTab.title")); //$NON-NLS-1$ fJavaEditorHoverConfigurationBlock= new JavaEditorHoverConfigurationBlock(this, fOverlayStore); item.setControl(fJavaEditorHoverConfigurationBlock.createControl(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.navigationTab.title")); //$NON-NLS-1$ item.setControl(createNavigationPage(folder)); initialize(); Dialog.applyDialogFont(folder); return folder; } private void initialize() { initializeFields(); for (int i= 0; i < fSyntaxColorListModel.length; i++) fSyntaxColorList.add(fSyntaxColorListModel[i][0]); fSyntaxColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) { fSyntaxColorList.select(0); handleSyntaxColorListSelection(); } } }); for (int i= 0; i < fAppearanceColorListModel.length; i++) fAppearanceColorList.add(fAppearanceColorListModel[i][0]); fAppearanceColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); } } }); for (int i= 0; i < fAnnotationColorListModel.length; i++) fAnnotationList.add(fAnnotationColorListModel[i][0]); fAnnotationList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAnnotationList != null && !fAnnotationList.isDisposed()) { fAnnotationList.select(0); handleAnnotationListSelection(); } } }); for (int i= 0; i < fContentAssistColorListModel.length; i++) fContentAssistColorList.add(fContentAssistColorListModel[i][0]); fContentAssistColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fContentAssistColorList != null && !fContentAssistColorList.isDisposed()) { fContentAssistColorList.select(0); handleContentAssistColorListSelection(); } } }); } private void initializeFields() { Iterator e= fColorButtons.keySet().iterator(); while (e.hasNext()) { ColorEditor c= (ColorEditor) e.next(); String key= (String) fColorButtons.get(c); RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); c.setColorValue(rgb); } e= fCheckBoxes.keySet().iterator(); while (e.hasNext()) { Button b= (Button) e.next(); String key= (String) fCheckBoxes.get(b); b.setSelection(fOverlayStore.getBoolean(key)); } e= fTextFields.keySet().iterator(); while (e.hasNext()) { Text t= (Text) e.next(); String key= (String) fTextFields.get(t); t.setText(fOverlayStore.getString(key)); } RGB rgb= PreferenceConverter.getColor(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR); fBackgroundColorEditor.setColorValue(rgb); boolean default_= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); fBackgroundDefaultRadioButton.setSelection(default_); fBackgroundCustomRadioButton.setSelection(!default_); fBackgroundColorButton.setEnabled(!default_); boolean closeJavaDocs= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS); fAddJavaDocTagsButton.setEnabled(closeJavaDocs); fEscapeStringsButton.setEnabled(fOverlayStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS)); boolean fillMethodArguments= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES); fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); boolean completionInserts= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); fCompletionInsertsRadioButton.setSelection(completionInserts); fCompletionOverwritesRadioButton.setSelection(! completionInserts); fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox.getSelection()); updateAutoactivationControls(); } private void initializeDefaultColors() { if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); } } private void updateAutoactivationControls() { boolean autoactivation= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); fAutoInsertDelayText.setEnabled(autoactivation); fAutoInsertDelayLabel.setEnabled(autoactivation); fAutoInsertJavaTriggerText.setEnabled(autoactivation); fAutoInsertJavaTriggerLabel.setEnabled(autoactivation); fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); fAutoInsertJavaDocTriggerLabel.setEnabled(autoactivation); } /* * @see PreferencePage#performOk() */ public boolean performOk() { fJavaEditorHoverConfigurationBlock.performOk(); fOverlayStore.setValue(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, computeStateMask(fBrowserLikeLinksKeyModifierText.getText())); fOverlayStore.propagate(); JavaPlugin.getDefault().savePluginPreferences(); return true; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fOverlayStore.loadDefaults(); initializeFields(); handleSyntaxColorListSelection(); handleAppearanceColorListSelection(); handleAnnotationListSelection(); handleContentAssistColorListSelection(); fJavaEditorHoverConfigurationBlock.performDefaults(); super.performDefaults(); fPreviewViewer.invalidateTextPresentation(); } /* * @see DialogPage#dispose() */ public void dispose() { if (fJavaTextTools != null) { fJavaTextTools.dispose(); fJavaTextTools= null; } if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) fBackgroundColor.dispose(); super.dispose(); } private Button addCheckBox(Composite parent, String label, String key, int indentation) { Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; gd.horizontalSpan= 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); fCheckBoxes.put(checkBox, key); return checkBox; } private Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { return getTextControl(addLabelledTextField(composite, label, key, textLimit, indentation, isNumber)); } private static Label getLabelControl(Control[] labelledTextField){ return (Label)labelledTextField[0]; } private static Text getTextControl(Control[] labelledTextField){ return (Text)labelledTextField[1]; } /** * Returns an array of size 2: * - first element is of type <code>Label</code> * - second element is of type <code>Text</code> * Use <code>getLabelControl</code> and <code>getTextControl</code> to get the 2 controls. */ private Control[] addLabelledTextField(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 new Control[]{labelControl, textControl}; } private String loadPreviewContentFromFile(String filename) { String line; String separator= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(512); BufferedReader reader= null; try { reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); while ((line= reader.readLine()) != null) { buffer.append(line); buffer.append(separator); } } catch (IOException io) { JavaPlugin.log(io); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) {} } } return buffer.toString(); } private void numberFieldChanged(Text textControl) { String number= textControl.getText(); IStatus status= validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) fOverlayStore.setValue((String) fTextFields.get(textControl), number); updateStatus(status); } private IStatus validatePositiveNumber(String number) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value < 0) status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } catch (NumberFormatException e) { status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } void updateStatus(IStatus status) { if (!status.matches(IStatus.ERROR)) { for (int i= 0; i < fNumberFields.size(); i++) { Text text= (Text) fNumberFields.get(i); IStatus s= validatePositiveNumber(text.getText()); status= StatusUtil.getMoreSevere(s, status); } } status= StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), status); status= StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), status); setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } }
45,356
Bug 45356 [typing] IndentAction: Pressing Tab at document begin gives IAE
Build 200310150800: Having a multi-line comment starting at document offset 0, the caret as well at offset 0 and pressing tab, the indent action gives an IAE. Reason: The constructor of status called at IndentAction#run() requires a non- null message parameter. The exception that was triggered in the first place results from a taking the previous line of the first one.
verified fixed
ad85cef
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-27T17:29:26Z
2003-10-22T10:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/IndentAction.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.actions; import java.util.ResourceBundle; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorExtension3; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner; import org.eclipse.jdt.internal.ui.text.JavaIndenter; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy; /** * Indents a line or range of lines in a Java document to its correct position. No complete * AST must be present, the indentation is computed using heuristics. The algorith used is fast for * single lines, but does not store any information and therefore not so efficient for large line * ranges. * * @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner * @see org.eclipse.jdt.internal.ui.text.JavaIndenter * @since 3.0 */ public class IndentAction extends TextEditorAction { /** The caret offset after an indent operation. */ private int fCaretOffset; /** * Whether this is the action invoked by TAB. When <code>true</code>, indentation behaves * differently to accomodate normal TAB operation. */ private final boolean fIsTabAction; /** * Creates a new instance. * * @param bundle the resource bundle * @param prefix the prefix to use for keys in <code>bundle</code> * @param editor the text editor */ public IndentAction(ResourceBundle bundle, String prefix, ITextEditor editor, boolean isTabAction) { super(bundle, prefix, editor); fIsTabAction= isTabAction; } /* * @see org.eclipse.jface.action.Action#run() */ public void run() { // update has been called by the framework if (!isEnabled() || !validateEditorInputState()) return; ITextSelection selection= getSelection(); final IDocument document= getDocument(); if (document != null) { final int offset= selection.getOffset(); final int length= selection.getLength(); final Position end= new Position(offset + length); final int firstLine, nLines; fCaretOffset= -1; try { document.addPosition(end); firstLine= document.getLineOfOffset(offset); // check for marginal (zero-length) lines int minusOne= length == 0 ? 0 : 1; nLines= document.getLineOfOffset(offset + length - minusOne) - firstLine + 1; } catch (BadLocationException e) { // will only happen on concurrent modification JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, null, e)); return; } Runnable runnable= new Runnable() { public void run() { IRewriteTarget target= (IRewriteTarget)getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); target.setRedraw(false); } try { JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); JavaIndenter indenter= new JavaIndenter(document, scanner); boolean hasChanged= false; for (int i= 0; i < nLines; i++) { hasChanged |= indentLine(document, firstLine + i, offset, indenter, scanner); } // update caret position: move to new position when indenting just one line // keep selection when indenting multiple int newOffset, newLength; if (fIsTabAction) { newOffset= fCaretOffset; newLength= 0; } else if (nLines > 1) { newOffset= offset; newLength= end.getOffset() - offset; } else { newOffset= fCaretOffset; newLength= 0; } // always reset the selection if anything was replaced // but not when we had a singleline nontab invocation if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length)) selectAndReveal(newOffset, newLength); document.removePosition(end); } catch (BadLocationException e) { // will only happen on concurrent modification JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, null, e)); } finally { if (target != null) { target.endCompoundChange(); target.setRedraw(true); } } } }; if (nLines > 50) { Display display= getTextEditor().getEditorSite().getWorkbenchWindow().getShell().getDisplay(); BusyIndicator.showWhile(display, runnable); } else runnable.run(); } } /** * Selects the given range on the editor. * * @param newOffset the selection offset * @param newLength the selection range */ private void selectAndReveal(int newOffset, int newLength) { Assert.isTrue(newOffset >= 0); Assert.isTrue(newLength >= 0); ITextEditor editor= getTextEditor(); if (editor instanceof JavaEditor) { ISourceViewer viewer= ((JavaEditor)editor).getViewer(); if (viewer != null) viewer.setSelectedRange(newOffset, newLength); } else // this is too intrusive, but will never get called anyway getTextEditor().selectAndReveal(newOffset, newLength); } /** * Indents a single line using the java heuristic scanner. Javadoc and multiline comments are * indented as specified by the <code>JavaDocAutoIndentStrategy</code>. * * @param document the document * @param line the line to be indented * @param caret the caret position * @param indenter the java indenter * @param scanner the heuristic scanner * @return <code>true</code> if <code>document</code> was modified, <code>false</code> otherwise * @throws BadLocationException if the document got changed concurrently */ private boolean indentLine(IDocument document, int line, int caret, JavaIndenter indenter, JavaHeuristicScanner scanner) throws BadLocationException { IRegion currentLine= document.getLineInformation(line); int offset= currentLine.getOffset(); String indent= null; if (offset < document.getLength()) { ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset); String type= partition.getType(); if (partition.getOffset() < offset && type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { // TODO this is a hack // what I want to do // new JavaDocAutoIndentStrategy().indentLineAtOffset(document, offset); // return; IRegion previousLine= document.getLineInformation(line - 1); DocumentCommand command= new DocumentCommand() { }; command.text= "\n"; //$NON-NLS-1$ command.offset= previousLine.getOffset() + previousLine.getLength(); new JavaDocAutoIndentStrategy(IJavaPartitions.JAVA_PARTITIONING).customizeDocumentCommand(document, command); int i= command.text.indexOf('*'); if (i != -1) indent= command.text.substring(1, i); else indent= command.text.substring(1); } } // standard java indentation if (indent == null) indent= indenter.computeIndentation(offset); // default is no indentation if (indent == null) indent= new String(); // change document: // get current white space int lineLength= currentLine.getLength(); int end= scanner.findNonWhitespaceForwardInAnyPartition(offset, offset + lineLength); if (end == JavaHeuristicScanner.NOT_FOUND) end= offset + lineLength; int length= end - offset; String currentIndent= document.get(offset, length); // if we are right before the text start / line end, and already after the insertion point // then just insert a tab. if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) { String tab= getTabEquivalent(); document.replace(caret, 0, tab); fCaretOffset= caret + tab.length(); return true; } // set the caret offset so it can be used when setting the selection if (caret >= offset && caret <= end) fCaretOffset= offset + indent.length(); else fCaretOffset= -1; // only change the document if it is a real change if (!indent.equals(currentIndent)) { document.replace(offset, length, indent); return true; } else return false; } /** * Returns the size in characters of a string. All characters count one, tabs count the editor's * preference for the tab display * * @param indent the string to be measured. * @return */ private int whiteSpaceLength(String indent) { if (indent == null) return 0; else { int size= 0; int l= indent.length(); int tabSize= JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); for (int i= 0; i < l; i++) size += indent.charAt(i) == '\t' ? tabSize : 1; return size; } } /** * Returns a tab equivalent, either as a tab character or as spaces, depending on the editor and * formatter preferences. * * @return a string representing one tab in the editor, never <code>null</code> */ private String getTabEquivalent() { String tab; if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SPACES_FOR_TABS)) { int size= JavaCore.getPlugin().getPluginPreferences().getInt(JavaCore.FORMATTER_TAB_SIZE); StringBuffer buf= new StringBuffer(); for (int i= 0; i< size; i++) buf.append(' '); tab= buf.toString(); } else tab= "\t"; //$NON-NLS-1$ return tab; } /** * Returns the editor's selection provider. * * @return the editor's selection provider or <code>null</code> */ private ISelectionProvider getSelectionProvider() { ITextEditor editor= getTextEditor(); if (editor != null) { return editor.getSelectionProvider(); } return null; } /* * @see org.eclipse.ui.texteditor.IUpdate#update() */ public void update() { super.update(); if (isEnabled()) if (fIsTabAction) setEnabled(canModifyEditor() && isSmartMode() && isValidSelection()); else setEnabled(canModifyEditor() && !getSelection().isEmpty()); } /** * Returns if the current selection is valid, i.e. whether it is empty and the caret in the * whitespace at the start of a line, or covers multiple lines. * * @return <code>true</code> if the selection is valid for an indent operation */ private boolean isValidSelection() { ITextSelection selection= getSelection(); if (selection.isEmpty()) return false; int offset= selection.getOffset(); int length= selection.getLength(); IDocument document= getDocument(); if (document == null) return false; try { IRegion firstLine= document.getLineInformationOfOffset(offset); int lineOffset= firstLine.getOffset(); // either the selection has to be empty and the caret in the WS at the line start // or the selection has to extend over multiple lines if (length == 0) return document.get(lineOffset, offset - lineOffset).trim().length() == 0; else // return lineOffset + firstLine.getLength() < offset + length; return false; // only enable for empty selections for now } catch (BadLocationException e) { } return false; } /** * Returns the smart preference state. * * @return <code>true</code> if smart mode is on, <code>false</code> otherwise */ private boolean isSmartMode() { ITextEditor editor= getTextEditor(); if (editor instanceof ITextEditorExtension3) return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT; return false; } /** * Returns the document currently displayed in the editor, or <code>null</code> if none can be * obtained. * * @return the current document or <code>null</code> */ private IDocument getDocument() { ITextEditor editor= getTextEditor(); if (editor != null) { IDocumentProvider provider= editor.getDocumentProvider(); IEditorInput input= editor.getEditorInput(); if (provider != null && input != null) return provider.getDocument(input); } return null; } /** * Returns the selection on the editor or an invalid selection if none can be obtained. Returns * never <code>null</code>. * * @return the current selection, never <code>null</code> */ private ITextSelection getSelection() { ISelectionProvider provider= getSelectionProvider(); if (provider != null) { ISelection selection= provider.getSelection(); if (selection instanceof ITextSelection) return (ITextSelection) selection; } // null object return TextSelection.emptySelection(); } }
45,614
Bug 45614 Refactoring - Pull up shows java code with bad colors [refactoring]
A dialog comes up under the Pull up refactoring that says"Select the methods to be removed in subtypes after pull up." The right hand panel shows java code for the selected method. It *assumes* the background color should be white, when it should not. It should be the same color as defined for Java editors. See #43368, #42704, #42703, & #41867
resolved fixed
89a48a3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-27T18:07:48Z
2003-10-27T18:40:00Z
org.eclipse.jdt.ui/ui
45,614
Bug 45614 Refactoring - Pull up shows java code with bad colors [refactoring]
A dialog comes up under the Pull up refactoring that says"Select the methods to be removed in subtypes after pull up." The right hand panel shows java code for the selected method. It *assumes* the background color should be white, when it should not. It should be the same color as defined for Java editors. See #43368, #42704, #42703, & #41867
resolved fixed
89a48a3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-27T18:07:48Z
2003-10-27T18:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/PullUpWizard.java
45,638
Bug 45638 [preferences] overwrite mode setting
Needs to be moved to Java>Editor>Typing.
resolved fixed
5156f79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-28T09:47:30Z
2003-10-28T00:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; 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.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; 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.source.SourceViewer; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; /* * The page for setting the editor options. */ public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX; private static final String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; private static final String DELIMITER= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ public final OverlayPreferenceStore.OverlayKey[] fKeys; private final String[][] fSyntaxColorListModel= new String[][] { { PreferencesMessages.getString("JavaEditorPreferencePage.multiLineComment"), PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.singleLineComment"), PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.strings"), PreferenceConstants.EDITOR_STRING_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.methodNames"), PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.operators"), PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaCommentTaskTags"), PreferenceConstants.EDITOR_TASK_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocLinks"), PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ }; private final String[][] fAppearanceColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColor2"), ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.findScopeColor2"), PreferenceConstants.EDITOR_FIND_SCOPE_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkedPositionColor2"), PreferenceConstants.EDITOR_LINKED_POSITION_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR}, //$NON-NLS-1$ }; private final String[][] fAnnotationColorListModel; private final String[][] fContentAssistColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND }, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND } //$NON-NLS-1$ }; private OverlayPreferenceStore fOverlayStore; private JavaTextTools fJavaTextTools; private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; private Map fColorButtons= new HashMap(); private Map fCheckBoxes= new HashMap(); private SelectionListener fCheckBoxListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { Button button= (Button) e.widget; fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); } }; private Map fTextFields= new HashMap(); private ModifyListener fTextFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { Text text= (Text) e.widget; fOverlayStore.setValue((String) fTextFields.get(text), text.getText()); } }; private ArrayList fNumberFields= new ArrayList(); private ModifyListener fNumberFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { numberFieldChanged((Text) e.widget); } }; private List fSyntaxColorList; private List fAppearanceColorList; private List fContentAssistColorList; private List fAnnotationList; private ColorEditor fSyntaxForegroundColorEditor; private ColorEditor fAppearanceColorEditor; private ColorEditor fAnnotationForegroundColorEditor; private ColorEditor fContentAssistColorEditor; private ColorEditor fBackgroundColorEditor; private Button fBackgroundDefaultRadioButton; private Button fBackgroundCustomRadioButton; private Button fBackgroundColorButton; private Button fBoldCheckBox; private Button fAddJavaDocTagsButton; private Button fEscapeStringsButton; private Button fGuessMethodArgumentsButton; private SourceViewer fPreviewViewer; private Color fBackgroundColor; private Control fAutoInsertDelayText; private Control fAutoInsertJavaTriggerText; private Control fAutoInsertJavaDocTriggerText; private Label fAutoInsertDelayLabel; private Label fAutoInsertJavaTriggerLabel; private Label fAutoInsertJavaDocTriggerLabel; private Button fShowInTextCheckBox; private Button fHighlightInTextCheckBox; private Button fShowInOverviewRulerCheckBox; private Button fShowInVerticalRulerCheckBox; private Text fBrowserLikeLinksKeyModifierText; private Button fBrowserLikeLinksCheckBox; private StatusInfo fBrowserLikeLinksKeyModifierStatus; private Button fCompletionInsertsRadioButton; private Button fCompletionOverwritesRadioButton; public JavaEditorPreferencePage() { setDescription(PreferencesMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); MarkerAnnotationPreferences markerAnnotationPreferences= new MarkerAnnotationPreferences(); fKeys= createOverlayStoreKeys(markerAnnotationPreferences); fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys); fAnnotationColorListModel= createAnnotationTypeListModel(markerAnnotationPreferences); } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys(MarkerAnnotationPreferences preferences) { ArrayList overlayKeys= new ArrayList(); Iterator e= preferences.getAnnotationPreferences().iterator(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOREGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BACKGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.EDITOR_TAB_WIDTH)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_STRING_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STRING_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TASK_TAG_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_TAG_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MATCHING_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINK_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CORRECTION_INDICATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SPACES_FOR_TABS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOACTIVATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOINSERT)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ADDIMPORT)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ESCAPE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); // overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FORMAT_JAVADOCS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_HOME_END)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMAT)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.FORMATTER_COMMENT_FORMATHTML)); while (e.hasNext()) { AnnotationPreference info= (AnnotationPreference) e.next(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, info.getColorPreferenceKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getTextPreferenceKey())); if (info.getHighlightPreferenceKey() != null) overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getHighlightPreferenceKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getOverviewRulerPreferenceKey())); if (info.getVerticalRulerPreferenceKey() != null) overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getVerticalRulerPreferenceKey())); } OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; overlayKeys.toArray(keys); return keys; } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); } private void handleSyntaxColorListSelection() { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fSyntaxForegroundColorEditor.setColorValue(rgb); fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); } private void handleAppearanceColorListSelection() { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAppearanceColorEditor.setColorValue(rgb); } private void handleContentAssistColorListSelection() { int i= fContentAssistColorList.getSelectionIndex(); String key= fContentAssistColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fContentAssistColorEditor.setColorValue(rgb); } private void handleAnnotationListSelection() { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAnnotationForegroundColorEditor.setColorValue(rgb); key= fAnnotationColorListModel[i][2]; fShowInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); key= fAnnotationColorListModel[i][3]; fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); key= fAnnotationColorListModel[i][4]; if (key != null) { fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); fHighlightInTextCheckBox.setEnabled(true); } else fHighlightInTextCheckBox.setEnabled(false); key= fAnnotationColorListModel[i][5]; if (key != null) { fShowInVerticalRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); fShowInVerticalRulerCheckBox.setEnabled(true); } else { fShowInVerticalRulerCheckBox.setSelection(true); fShowInVerticalRulerCheckBox.setEnabled(false); } } private Control createSyntaxPage(Composite parent) { Composite colorComposite= new Composite(parent, SWT.NULL); colorComposite.setLayout(new GridLayout()); Group backgroundComposite= new Group(colorComposite, SWT.SHADOW_ETCHED_IN); backgroundComposite.setLayout(new RowLayout()); backgroundComposite.setText(PreferencesMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ SelectionListener backgroundSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean custom= fBackgroundCustomRadioButton.getSelection(); fBackgroundColorButton.setEnabled(custom); fOverlayStore.setValue(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, !custom); } public void widgetDefaultSelected(SelectionEvent e) {} }; fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundDefaultRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundCustomRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundColorEditor= new ColorEditor(backgroundComposite); fBackgroundColorButton= fBackgroundColorEditor.getButton(); Label label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite editorComposite= new Composite(colorComposite, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); editorComposite.setLayoutData(gd); fSyntaxColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fSyntaxColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); label= new Label(stylesComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fSyntaxForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fBoldCheckBox= new Button(stylesComposite, SWT.CHECK); fBoldCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fBoldCheckBox.setLayoutData(gd); label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control previewer= createPreviewer(colorComposite); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(20); gd.heightHint= convertHeightInCharsToPixels(5); previewer.setLayoutData(gd); fSyntaxColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleSyntaxColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fSyntaxForegroundColorEditor.getColorValue()); } }); fBackgroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { PreferenceConverter.setValue(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, fBackgroundColorEditor.getColorValue()); } }); fBoldCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fSyntaxColorList.getSelectionIndex(); String key= fSyntaxColorListModel[i][1]; fOverlayStore.setValue(key + BOLD, fBoldCheckBox.getSelection()); } }); return colorComposite; } private Control createPreviewer(Composite parent) { Preferences coreStore= createTemporaryCorePreferenceStore(); fJavaTextTools= new JavaTextTools(fOverlayStore, coreStore, false); fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); fPreviewViewer.configure(new JavaSourceViewerConfiguration(fJavaTextTools, null, IJavaPartitions.JAVA_PARTITIONING)); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); fPreviewViewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(fPreviewViewer, fJavaTextTools); fPreviewViewer.setEditable(false); String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ IDocument document= new Document(content); fJavaTextTools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING); fPreviewViewer.setDocument(document); return fPreviewViewer.getControl(); } private Preferences createTemporaryCorePreferenceStore() { Preferences result= new Preferences(); result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$ return result; } private Control createAppearancePage(Composite parent) { Composite appearanceComposite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; appearanceComposite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ addTextField(appearanceComposite, label, PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ addTextField(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, 0); Label l= new Label(appearanceComposite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(appearanceComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(appearanceComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fAppearanceColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fAppearanceColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fAppearanceColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fAppearanceColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAppearanceColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue()); } }); return appearanceComposite; } private Control createAnnotationsPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String text= PreferencesMessages.getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$ addCheckBox(composite, text, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); text= PreferencesMessages.getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ addCheckBox(composite, text, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); addFiller(composite); Label label= new Label(composite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationPresentationOptions")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; label.setLayoutData(gd); Composite editorComposite= new Composite(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAnnotationList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(10); fAnnotationList.setLayoutData(gd); Composite optionsComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; optionsComposite.setLayout(layout); optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); fShowInTextCheckBox= new Button(optionsComposite, SWT.CHECK); fShowInTextCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInText")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fShowInTextCheckBox.setLayoutData(gd); fHighlightInTextCheckBox= new Button(optionsComposite, SWT.CHECK); fHighlightInTextCheckBox.setText(PreferencesMessages.getString("TextEditorPreferencePage.annotations.highlightInText")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fHighlightInTextCheckBox.setLayoutData(gd); fShowInOverviewRulerCheckBox= new Button(optionsComposite, SWT.CHECK); fShowInOverviewRulerCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fShowInOverviewRulerCheckBox.setLayoutData(gd); fShowInVerticalRulerCheckBox= new Button(optionsComposite, SWT.CHECK); fShowInVerticalRulerCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInVerticalRuler")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fShowInVerticalRulerCheckBox.setLayoutData(gd); label= new Label(optionsComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fAnnotationForegroundColorEditor= new ColorEditor(optionsComposite); Button foregroundColorButton= fAnnotationForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fAnnotationList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAnnotationListSelection(); } }); fShowInTextCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][2]; fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection()); } }); fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][4]; fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection()); } }); fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][3]; fOverlayStore.setValue(key, fShowInOverviewRulerCheckBox.getSelection()); } }); fShowInVerticalRulerCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][5]; fOverlayStore.setValue(key, fShowInVerticalRulerCheckBox.getSelection()); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAnnotationList.getSelectionIndex(); String key= fAnnotationColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAnnotationForegroundColorEditor.getColorValue()); } }); return composite; } private String[][] createAnnotationTypeListModel(MarkerAnnotationPreferences preferences) { ArrayList listModelItems= new ArrayList(); Iterator e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { AnnotationPreference info= (AnnotationPreference) e.next(); listModelItems.add(new String[] { info.getPreferenceLabel(), info.getColorPreferenceKey(), info.getTextPreferenceKey(), info.getOverviewRulerPreferenceKey(), info.getHighlightPreferenceKey(), info.getVerticalRulerPreferenceKey()}); } String[][] items= new String[listModelItems.size()][]; listModelItems.toArray(items); return items; } private Control createTypingPage(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 1; composite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.subWordNavigation"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); addFiller(composite); Group group= new Group(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; group.setLayout(layout); group.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ label= PreferencesMessages.getString("JavaEditorPreferencePage.wrapStrings"); //$NON-NLS-1$ Button button= addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.escapeStrings"); //$NON-NLS-1$ fEscapeStringsButton= addCheckBox(group, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS, 1); createDependency(button, fEscapeStringsButton); label= PreferencesMessages.getString("JavaEditorPreferencePage.smartPaste"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeStrings"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBrackets"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBraces"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); //$NON-NLS-1$ button= addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.addJavaDocTags"); //$NON-NLS-1$ fAddJavaDocTagsButton= addCheckBox(group, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); createDependency(button, fAddJavaDocTagsButton); // label= PreferencesMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); //$NON-NLS-1$ // addCheckBox(group, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); return composite; } private void addFiller(Composite composite) { Label filler= new Label(composite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; filler.setLayoutData(gd); } private static void indent(Control control) { GridData gridData= new GridData(); gridData.horizontalIndent= 20; control.setLayoutData(gridData); } private static void createDependency(final Button master, final Control slave) { indent(slave); master.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) {} }); } private Control createContentAssistPage(Composite parent) { Composite contentAssistComposite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; contentAssistComposite.setLayout(layout); addCompletionRadioButtons(contentAssistComposite); String label; label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOINSERT, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$ addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ADDIMPORT, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ Button button= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ fGuessMethodArgumentsButton= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0); createDependency(button, fGuessMethodArgumentsButton); label= PreferencesMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$ final Button autoactivation= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION, 0); autoactivation.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { updateAutoactivationControls(); } }); Control[] labelledTextField; label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$ labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 4, 0, true); fAutoInsertDelayLabel= getLabelControl(labelledTextField); fAutoInsertDelayText= getTextControl(labelledTextField); label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$ labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, 4, 0, false); fAutoInsertJavaTriggerLabel= getLabelControl(labelledTextField); fAutoInsertJavaTriggerText= getTextControl(labelledTextField); label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$ labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, 4, 0, false); fAutoInsertJavaDocTriggerLabel= getLabelControl(labelledTextField); fAutoInsertJavaDocTriggerText= getTextControl(labelledTextField); Label l= new Label(contentAssistComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.colorOptions")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(contentAssistComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fContentAssistColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fContentAssistColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fContentAssistColorEditor= new ColorEditor(stylesComposite); Button colorButton= fContentAssistColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; colorButton.setLayoutData(gd); fContentAssistColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleContentAssistColorListSelection(); } }); colorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fContentAssistColorList.getSelectionIndex(); String key= fContentAssistColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fContentAssistColorEditor.getColorValue()); } }); return contentAssistComposite; } private void addCompletionRadioButtons(Composite contentAssistComposite) { Composite completionComposite= new Composite(contentAssistComposite, SWT.NONE); GridData ccgd= new GridData(); ccgd.horizontalSpan= 2; completionComposite.setLayoutData(ccgd); GridLayout ccgl= new GridLayout(); ccgl.marginWidth= 0; ccgl.numColumns= 2; completionComposite.setLayout(ccgl); SelectionListener completionSelectionListener= new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { boolean insert= fCompletionInsertsRadioButton.getSelection(); fOverlayStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, insert); } }; fCompletionInsertsRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT); fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); //$NON-NLS-1$ fCompletionInsertsRadioButton.setLayoutData(new GridData()); fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); fCompletionOverwritesRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT); fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); //$NON-NLS-1$ fCompletionOverwritesRadioButton.setLayoutData(new GridData()); fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); } private Control createNavigationPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String text= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); //$NON-NLS-1$ fBrowserLikeLinksCheckBox= addCheckBox(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean state= fBrowserLikeLinksCheckBox.getSelection(); fBrowserLikeLinksKeyModifierText.setEnabled(state); handleBrowserLikeLinksKeyModifierModified(); } public void widgetDefaultSelected(SelectionEvent e) { } }); // Text field for modifier string text= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); //$NON-NLS-1$ fBrowserLikeLinksKeyModifierText= addTextField(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, 0, false); fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); if (computeStateMask(fOverlayStore.getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { // Fix possible illegal modifier string int stateMask= fOverlayStore.getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); if (stateMask == -1) fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierText.setText(EditorUtility.getModifierString(stateMask)); } fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { private boolean isModifierCandidate; public void keyPressed(KeyEvent e) { isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0; } public void keyReleased(KeyEvent e) { if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { String modifierString= fBrowserLikeLinksKeyModifierText.getText(); Point selection= fBrowserLikeLinksKeyModifierText.getSelection(); int i= selection.x - 1; while (i > -1 && Character.isWhitespace(modifierString.charAt(i))) { i--; } boolean needsPrefixDelimiter= i > -1 && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); i= selection.y; while (i < modifierString.length() && Character.isWhitespace(modifierString.charAt(i))) { i++; } boolean needsPostfixDelimiter= i < modifierString.length() && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); String insertString; if (needsPrefixDelimiter && needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPrefixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else insertString= Action.findModifierString(e.stateMask); fBrowserLikeLinksKeyModifierText.insert(insertString); } } }); fBrowserLikeLinksKeyModifierText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleBrowserLikeLinksKeyModifierModified(); } }); return composite; } private void handleBrowserLikeLinksKeyModifierModified() { String modifiers= fBrowserLikeLinksKeyModifierText.getText(); int stateMask= computeStateMask(modifiers); if (fBrowserLikeLinksCheckBox.getSelection() && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { if (stateMask == -1) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); //$NON-NLS-1$ setValid(false); StatusUtil.applyToStatusLine(this, fBrowserLikeLinksKeyModifierStatus); } else { fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); updateStatus(fBrowserLikeLinksKeyModifierStatus); } } private IStatus getBrowserLikeLinksKeyModifierStatus() { if (fBrowserLikeLinksKeyModifierStatus == null) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); return fBrowserLikeLinksKeyModifierStatus; } /** * Computes the state mask for the given modifier string. * * @param modifiers the string with the modifiers, separated by '+', '-', ';', ',' or '.' * @return the state mask or -1 if the input is invalid */ private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDefaultColors(); fOverlayStore.load(); fOverlayStore.start(); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); TabItem item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ item.setControl(createAppearancePage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ item.setControl(createSyntaxPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist")); //$NON-NLS-1$ item.setControl(createContentAssistPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationsTab.title")); //$NON-NLS-1$ item.setControl(createAnnotationsPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle")); //$NON-NLS-1$ item.setControl(createTypingPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.hoverTab.title")); //$NON-NLS-1$ fJavaEditorHoverConfigurationBlock= new JavaEditorHoverConfigurationBlock(this, fOverlayStore); item.setControl(fJavaEditorHoverConfigurationBlock.createControl(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.navigationTab.title")); //$NON-NLS-1$ item.setControl(createNavigationPage(folder)); initialize(); Dialog.applyDialogFont(folder); return folder; } private void initialize() { initializeFields(); for (int i= 0; i < fSyntaxColorListModel.length; i++) fSyntaxColorList.add(fSyntaxColorListModel[i][0]); fSyntaxColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) { fSyntaxColorList.select(0); handleSyntaxColorListSelection(); } } }); for (int i= 0; i < fAppearanceColorListModel.length; i++) fAppearanceColorList.add(fAppearanceColorListModel[i][0]); fAppearanceColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); } } }); for (int i= 0; i < fAnnotationColorListModel.length; i++) fAnnotationList.add(fAnnotationColorListModel[i][0]); fAnnotationList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAnnotationList != null && !fAnnotationList.isDisposed()) { fAnnotationList.select(0); handleAnnotationListSelection(); } } }); for (int i= 0; i < fContentAssistColorListModel.length; i++) fContentAssistColorList.add(fContentAssistColorListModel[i][0]); fContentAssistColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fContentAssistColorList != null && !fContentAssistColorList.isDisposed()) { fContentAssistColorList.select(0); handleContentAssistColorListSelection(); } } }); } private void initializeFields() { Iterator e= fColorButtons.keySet().iterator(); while (e.hasNext()) { ColorEditor c= (ColorEditor) e.next(); String key= (String) fColorButtons.get(c); RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); c.setColorValue(rgb); } e= fCheckBoxes.keySet().iterator(); while (e.hasNext()) { Button b= (Button) e.next(); String key= (String) fCheckBoxes.get(b); b.setSelection(fOverlayStore.getBoolean(key)); } e= fTextFields.keySet().iterator(); while (e.hasNext()) { Text t= (Text) e.next(); String key= (String) fTextFields.get(t); t.setText(fOverlayStore.getString(key)); } RGB rgb= PreferenceConverter.getColor(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR); fBackgroundColorEditor.setColorValue(rgb); boolean default_= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); fBackgroundDefaultRadioButton.setSelection(default_); fBackgroundCustomRadioButton.setSelection(!default_); fBackgroundColorButton.setEnabled(!default_); boolean closeJavaDocs= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS); fAddJavaDocTagsButton.setEnabled(closeJavaDocs); fEscapeStringsButton.setEnabled(fOverlayStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS)); boolean fillMethodArguments= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES); fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); boolean completionInserts= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); fCompletionInsertsRadioButton.setSelection(completionInserts); fCompletionOverwritesRadioButton.setSelection(! completionInserts); fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox.getSelection()); updateAutoactivationControls(); } private void initializeDefaultColors() { if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); } } private void updateAutoactivationControls() { boolean autoactivation= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); fAutoInsertDelayText.setEnabled(autoactivation); fAutoInsertDelayLabel.setEnabled(autoactivation); fAutoInsertJavaTriggerText.setEnabled(autoactivation); fAutoInsertJavaTriggerLabel.setEnabled(autoactivation); fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); fAutoInsertJavaDocTriggerLabel.setEnabled(autoactivation); } /* * @see PreferencePage#performOk() */ public boolean performOk() { fJavaEditorHoverConfigurationBlock.performOk(); fOverlayStore.setValue(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, computeStateMask(fBrowserLikeLinksKeyModifierText.getText())); fOverlayStore.propagate(); JavaPlugin.getDefault().savePluginPreferences(); return true; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fOverlayStore.loadDefaults(); initializeFields(); handleSyntaxColorListSelection(); handleAppearanceColorListSelection(); handleAnnotationListSelection(); handleContentAssistColorListSelection(); fJavaEditorHoverConfigurationBlock.performDefaults(); super.performDefaults(); fPreviewViewer.invalidateTextPresentation(); } /* * @see DialogPage#dispose() */ public void dispose() { if (fJavaTextTools != null) { fJavaTextTools.dispose(); fJavaTextTools= null; } if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) fBackgroundColor.dispose(); super.dispose(); } private Button addCheckBox(Composite parent, String label, String key, int indentation) { Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; gd.horizontalSpan= 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); fCheckBoxes.put(checkBox, key); return checkBox; } private Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { return getTextControl(addLabelledTextField(composite, label, key, textLimit, indentation, isNumber)); } private static Label getLabelControl(Control[] labelledTextField){ return (Label)labelledTextField[0]; } private static Text getTextControl(Control[] labelledTextField){ return (Text)labelledTextField[1]; } /** * Returns an array of size 2: * - first element is of type <code>Label</code> * - second element is of type <code>Text</code> * Use <code>getLabelControl</code> and <code>getTextControl</code> to get the 2 controls. */ private Control[] addLabelledTextField(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 new Control[]{labelControl, textControl}; } private String loadPreviewContentFromFile(String filename) { String line; String separator= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(512); BufferedReader reader= null; try { reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); while ((line= reader.readLine()) != null) { buffer.append(line); buffer.append(separator); } } catch (IOException io) { JavaPlugin.log(io); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) {} } } return buffer.toString(); } private void numberFieldChanged(Text textControl) { String number= textControl.getText(); IStatus status= validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) fOverlayStore.setValue((String) fTextFields.get(textControl), number); updateStatus(status); } private IStatus validatePositiveNumber(String number) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value < 0) status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } catch (NumberFormatException e) { status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } void updateStatus(IStatus status) { if (!status.matches(IStatus.ERROR)) { for (int i= 0; i < fNumberFields.size(); i++) { Text text= (Text) fNumberFields.get(i); IStatus s= validatePositiveNumber(text.getText()); status= StatusUtil.getMoreSevere(s, status); } } status= StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), status); status= StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), status); setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } }
45,638
Bug 45638 [preferences] overwrite mode setting
Needs to be moved to Java>Editor>Typing.
resolved fixed
5156f79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-28T09:47:30Z
2003-10-28T00:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/WorkInProgressPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; 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.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.quickdiff.QuickDiff; import org.eclipse.ui.texteditor.quickdiff.ReferenceProviderDescriptor; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Preference page for work in progress. */ public class WorkInProgressPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { /** prefix for resources */ private static final String PREFIX= "WorkInProgress."; //$NON-NLS-1$ public final static String PREF_FORMATTER= "use_new_formatter"; //$NON-NLS-1$ /** * All FieldEditors except <code>smartTyping</code>, whose enable state * is controlled by the smartTyping preference. */ private Set fSmartTypingItems= new HashSet(); private List fCheckBoxes; private List fRadioButtons; private List fTextControls; /** List for the reference provider default. */ private org.eclipse.swt.widgets.List fQuickDiffProviderList; /** The reference provider default's list model. */ private String[][] fQuickDiffProviderListModel; /** Button controlling default setting of the selected reference provider. */ private Button fSetDefaultButton; /** * creates a new preference page. */ public WorkInProgressPreferencePage() { setPreferenceStore(getPreferenceStore()); fRadioButtons= new ArrayList(); fCheckBoxes= new ArrayList(); fTextControls= new ArrayList(); List providers= new QuickDiff().getReferenceProviderDescriptors(); fQuickDiffProviderListModel= createQuickDiffReferenceListModel(providers); } private String[][] createQuickDiffReferenceListModel(List providers) { ArrayList listModelItems= new ArrayList(); for (Iterator it= providers.iterator(); it.hasNext();) { ReferenceProviderDescriptor provider= (ReferenceProviderDescriptor) it.next(); String label= provider.getLabel(); int i= label.indexOf('&'); while (i >= 0) { if (i < label.length()) label= label.substring(0, i) + label.substring(i+1); else label.substring(0, i); i= label.indexOf('&'); } listModelItems.add(new String[] { provider.getId(), label }); } String[][] items= new String[listModelItems.size()][]; listModelItems.toArray(items); return items; } private void handleProviderListSelection() { int i= fQuickDiffProviderList.getSelectionIndex(); boolean b= getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0]); fSetDefaultButton.setEnabled(!b); } private Button addCheckBox(Composite parent, String label, String key) { GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); Button button= new Button(parent, SWT.CHECK); button.setText(label); button.setData(key); button.setLayoutData(gd); button.setSelection(getPreferenceStore().getBoolean(key)); fCheckBoxes.add(button); return button; } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), "WORK_IN_PROGRESS_PREFERENCE_PAGE"); //$NON-NLS-1$ } protected Control createContents(Composite parent) { initializeDialogUnits(parent); Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginWidth= 0; layout.verticalSpacing= convertVerticalDLUsToPixels(10); layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); result.setLayout(layout); Group group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "editor")); //$NON-NLS-1$ addCheckBox(group, PreferencesMessages.getString(PREFIX + "markOccurrences"), PreferenceConstants.EDITOR_MARK_OCCURRENCES); //$NON-NLS-1$ addCheckBox(group, PreferencesMessages.getString(PREFIX + "overwriteMode"), PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE); //$NON-NLS-1$ createSpacer(group, 1); Label label= new Label(group, SWT.NONE); label.setText(PreferencesMessages.getString(PREFIX + "smartTyping.label")); //$NON-NLS-1$ Button button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartSemicolon"), PreferenceConstants.EDITOR_SMART_SEMICOLON); //$NON-NLS-1$ fSmartTypingItems.add(button); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartOpeningBrace"), PreferenceConstants.EDITOR_SMART_OPENING_BRACE); //$NON-NLS-1$ fSmartTypingItems.add(button); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartTab"), PreferenceConstants.EDITOR_SMART_TAB); //$NON-NLS-1$ fSmartTypingItems.add(button); /* line change bar */ group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "quickdiff")); //$NON-NLS-1$ Label l= new Label(group, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "showQuickDiffPerDefault"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickdiff.characterMode"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_CHARACTER_MODE); //$NON-NLS-1$ l= new Label(group, SWT.LEFT ); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(group, SWT.LEFT); l.setText(PreferencesMessages.getString(PREFIX + "quickdiff.referenceprovidertitle")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(group, 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); fQuickDiffProviderList= new org.eclipse.swt.widgets.List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(4); fQuickDiffProviderList.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)); fSetDefaultButton= new Button(stylesComposite, SWT.PUSH); fSetDefaultButton.setText(PreferencesMessages.getString(PREFIX + "quickdiff.setDefault")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fSetDefaultButton.setLayoutData(gd); fQuickDiffProviderList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleProviderListSelection(); } }); fSetDefaultButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fQuickDiffProviderList.getSelectionIndex(); for (int j= 0; j < fQuickDiffProviderListModel.length; j++) { if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[j][0])) { fQuickDiffProviderList.remove(j); fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1], j); } if (i == j) { fQuickDiffProviderList.remove(j); fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1] + " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"), j); //$NON-NLS-1$//$NON-NLS-2$ } } fSetDefaultButton.setEnabled(false); fQuickDiffProviderList.setSelection(i); fQuickDiffProviderList.redraw(); getPreferenceStore().setValue(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER, fQuickDiffProviderListModel[i][0]); } }); for (int i= 0; i < fQuickDiffProviderListModel.length; i++) { String sLabel= fQuickDiffProviderListModel[i][1]; if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0])) sLabel += " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"); //$NON-NLS-1$ //$NON-NLS-2$ fQuickDiffProviderList.add(sLabel); } fQuickDiffProviderList.getDisplay().asyncExec(new Runnable() { public void run() { if (fQuickDiffProviderList != null && !fQuickDiffProviderList.isDisposed()) { fQuickDiffProviderList.select(0); handleProviderListSelection(); } } }); group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "quickassist.group")); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickassist.option"), PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB); //$NON-NLS-1$ //$NON-NLS-2$ group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "formatter")); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "formatter.option"), PREF_FORMATTER); //$NON-NLS-1$ return result; } /* * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } protected void createSpacer(Composite composite, int columnSpan) { Label label= new Label(composite, SWT.NONE); GridData gd= new GridData(); gd.horizontalSpan= columnSpan; label.setLayoutData(gd); } /* * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() */ protected IPreferenceStore doGetPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); button.setSelection(store.getDefaultBoolean(key)); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); String[] info= (String[]) button.getData(); button.setSelection(info[1].equals(store.getDefaultString(info[0]))); } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); text.setText(store.getDefaultString(key)); } handleProviderListSelection(); super.performDefaults(); } /* * @see IPreferencePage#performOk() */ public boolean performOk() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); store.setValue(key, button.getSelection()); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); if (button.getSelection()) { String[] info= (String[]) button.getData(); store.setValue(info[0], info[1]); } } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); store.setValue(key, text.getText()); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /** * @param store */ public static void initDefaults(IPreferenceStore store) { store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, false); store.setDefault(PreferenceConstants.EDITOR_SMART_SEMICOLON, false); store.setDefault(PreferenceConstants.EDITOR_SMART_OPENING_BRACE, false); store.setDefault(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB, false); store.setDefault(PREF_FORMATTER, false); store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, false); } }
45,638
Bug 45638 [preferences] overwrite mode setting
Needs to be moved to Java>Editor>Typing.
resolved fixed
5156f79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-28T09:47:30Z
2003-10-28T00:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.action.Action; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.text.IJavaColorConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage; /** * 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 controls if quick assist light bulbs are shown. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> light bulbs are shown * for quick assists. * </p> */ public static final String APPEARANCE_QUICKASSIST_LIGHTBULB="org.eclipse.jdt.quickassist.lightbulb"; //$NON-NLS-1$ /** * A named preference that defines the pattern used for package name compression. * <p> * Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern * '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'. * </p> */ public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$ /** * A named preference that controls if package name compression is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW */ public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$ /** * A named preference that controls if empty inner packages are folded in * the hierarchical mode of the package explorer. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> empty * inner packages are folded. * </p> * @since 2.1 */ public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$ /** * A named preference that defines how member elements are ordered by the * Java views using the <code>JavaElementSorter</code>. * <p> * Value is of type <code>String</code>: A comma separated list of the * following entries. Each entry must be in the list, no duplication. List * order defines the sort order. * <ul> * <li><b>T</b>: Types</li> * <li><b>C</b>: Constructors</li> * <li><b>I</b>: Initializers</li> * <li><b>M</b>: Methods</li> * <li><b>F</b>: Fields</li> * <li><b>SI</b>: Static Initializers</li> * <li><b>SM</b>: Static Methods</li> * <li><b>SF</b>: Static Fields</li> * </ul> * </p> * @since 2.1 */ public static final String APPEARANCE_MEMBER_SORT_ORDER= "outlinesortoption"; //$NON-NLS-1$ /** * A named preference that controls if prefix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of prefixes to be removed from a local variable to compute setter * and gettter names. * <p> * Value is of type <code>String</code>: comma separated list of prefixed * </p> * * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$ /** * A named preference that controls if suffix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of suffixes to be removed from a local variable to compute setter * and getter names. * <p> * Value is of type <code>String</code>: comma separated list of suffixes * </p> * @deprecated Use setting from JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_SUFFIXES and CODEASSIST_STATIC_FIELD_SUFFIXES) */ public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ /** * A named preference that controls whether the keyword "this" will be added * automatically to field accesses in autogenerated methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public static final String CODEGEN_KEYWORD_THIS= "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$ /** * A named preference that controls whether to use the prefix "is" or the prefix "get" for * automatically created getters which return a boolean field. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public static final String CODEGEN_IS_FOR_GETTERS= "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$ /** * A named preference that controls if comment stubs will be added * automatically to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$ /** * A named preference that controls if a comment stubs will be added * automatocally to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precice). */ public static final String CODEGEN__JAVADOC_STUBS= CODEGEN_ADD_COMMENTS; /** * A named preference that controls if a non-javadoc comment gets added to methods generated via the * "Override Methods" operation. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the overriding method comment. */ public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$ /** * A named preference that controls if a file comment gets added to newly created files. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the new type code template. */ public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$ /** * A named preference that holds a list of comma separated package names. The list specifies the import order used by * the "Organize Imports" opeation. * <p> * Value is of type <code>String</code>: semicolon separated list of package * names * </p> */ public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.jdt.ui.importorder"; //$NON-NLS-1$ /** * A named preference that specifies the number of imports added before a star-import declaration is used. * <p> * Value is of type <code>Int</code>: positive value specifing the number of non star-import is used * </p> */ public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.jdt.ui.ondemandthreshold"; //$NON-NLS-1$ /** * A named preferences that controls if types that start with a lower case letters get added by the * "Organize Import" operation. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.jdt.ui.ignorelowercasenames"; //$NON-NLS-1$ /** * A named preference that speficies whether children of a compilation unit are shown in the package explorer. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String SHOW_CU_CHILDREN= "org.eclipse.jdt.ui.packages.cuchildren"; //$NON-NLS-1$ /** * A named preference that controls whether the package explorer's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the hierarchy view's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_TYPEHIERARCHY_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the projects view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PROJECTS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.projectstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the packages view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.packagestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the types view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_TYPES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.typestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the members view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_MEMBERS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.memberstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether new projects are generated using source and output folder. * <p> * Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and * output folder. If <code>false</code> source and output folder equals to the project. * </p> */ public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ /** * A named preference that specifies the source folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ /** * A named preference that specifies the output folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ /** * A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library * consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the * JRE on the new project's classpath. * <p> * Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries. * <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients * should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string * and the methods <code>decodeJRELibraryDescription(String)</code> and <code> * decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array * of classpath entries from an encoded string. * </p> * * @see #NEWPROJECT_JRELIBRARY_INDEX * @see #encodeJRELibrary(String, IClasspathEntry[]) * @see #decodeJRELibraryDescription(String) * @see #decodeJRELibraryClasspathEntries(String) */ public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$ /** * A named preferences that specifies the current active JRE library. * <p> * Value is of type <code>Int</code>: an index into the list of possible JRE libraries. * </p> * * @see #NEWPROJECT_JRELIBRARY_LIST */ public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$ /** * A named preference that controls if a new type hierarchy gets opened in a * new type hierarchy perspective or inside the type hierarchy view part. * <p> * Value is of type <code>String</code>: possible values are <code> * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code> * OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>. * </p> * * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART */ public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$ /** * A named preference that controls the behaviour when double clicking on a container in the packages view. * <p> * Value is of type <code>String</code>: possible values are <code> * DOUBLE_CLICK_GOES_INTO</code> or <code> * DOUBLE_CLICK_EXPANDS</code>. * </p> * * @see #DOUBLE_CLICK_EXPANDS * @see #DOUBLE_CLICK_GOES_INTO */ public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$ /** * A named preference that controls whether Java views update their presentation while editing or when saving the * content of an editor. * <p> * Value is of type <code>String</code>: possible values are <code> * UPDATE_ON_SAVE</code> or <code> * UPDATE_WHILE_EDITING</code>. * </p> * * @see #UPDATE_ON_SAVE * @see #UPDATE_WHILE_EDITING */ public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$ /** * A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard. * <p> * Value is of type <code>String</code>. * </p> */ public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$ /** * A named preference that defines whether hint to make hover sticky should be shown. * * @see JavaUI * @since 3.0 */ public static String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE= "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$ /** * A named preference that defines the key for the hover modifiers. * * @see JavaUI * @since 2.1 */ public static final String EDITOR_TEXT_HOVER_MODIFIERS= "hoverModifiers"; //$NON-NLS-1$ /** * A named preference that defines the key for the hover modifier state masks. * The value is only used if the value of <code>EDITOR_TEXT_HOVER_MODIFIERS</code> * cannot be resolved to valid SWT modifier bits. * * @see JavaUI * @see #EDITOR_TEXT_HOVER_MODIFIERS * @since 2.1.1 */ public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS= "hoverModifierMasks"; //$NON-NLS-1$ /** * The id of the best match hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 */ public static String ID_BESTMATCH_HOVER= "org.eclipse.jdt.ui.BestMatchHover"; //$NON-NLS-1$ /** * The id of the source code hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 */ public static String ID_SOURCE_HOVER= "org.eclipse.jdt.ui.JavaSourceHover"; //$NON-NLS-1$ /** * The id of the javadoc hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 */ public static String ID_JAVADOC_HOVER= "org.eclipse.jdt.ui.JavadocHover"; //$NON-NLS-1$ /** * The id of the problem hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 */ public static String ID_PROBLEM_HOVER= "org.eclipse.jdt.ui.ProblemHover"; //$NON-NLS-1$ /** * 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> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ 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> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$ /** * Print margin column. Int value. * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ 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> * * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows warning indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ 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 'escape strings' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public final static String EDITOR_ESCAPE_STRINGS= "escapeStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close brackets' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close braces' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close java docs' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'add JavaDoc tags' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$ /** * A named preference that controls whether the 'format Javadoc tags' * feature is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_FORMAT_JAVADOCS= "autoFormatJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart paste' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart home-end' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; /** * A named preference that controls whether the 'sub-word navigation' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SUB_WORD_NAVIGATION= "subWordNavigation"; //$NON-NLS-1$ /** * 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> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ 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> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ 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 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$ /** * A named preference that holds the color used to render linked positions inside code templates. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$ /** * A named preference that holds the color used as the text foreground. * This value has not effect if the system default color is used. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; /** * A named preference that describes if the system default foreground color * is used as the text foreground. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; /** * A named preference that holds the color used as the text background. * This value has not effect if the system default color is used. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; /** * A named preference that describes if the system default background color * is used as the text background. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; /** * Preference key suffix for bold text style preference keys. * * @since 2.1 */ public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$ /** * A named preference that holds the color used to render multi line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT; /** * The symbolic font name for the Java editor text font * (value <code>"org.eclipse.jdt.ui.editors.textfont"</code>). * * @since 2.1 */ public final static String EDITOR_TEXT_FONT= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$ /** * A named preference that controls whether multi line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render single line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT; /** * A named preference that controls whether sinle line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD; /** * A named preference that controls whether keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render string constants. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING; /** * A named preference that controls whether string constants are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render method names. * <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 3.0 */ public final static String EDITOR_JAVA_METHOD_NAME_COLOR= IJavaColorConstants.JAVA_METHOD_NAME; /** * A named preference that controls whether method names are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_METHOD_NAME_BOLD= IJavaColorConstants.JAVA_METHOD_NAME + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render operators and 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 * @since 3.0 */ public final static String EDITOR_JAVA_OPERATOR_COLOR= IJavaColorConstants.JAVA_OPERATOR; /** * A named preference that controls whether operators and brackets are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_OPERATOR_BOLD= IJavaColorConstants.JAVA_OPERATOR + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT; /** * A named preference that controls whether Java default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render task tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_TASK_TAG_COLOR= IJavaColorConstants.TASK_TAG; /** * A named preference that controls whether task tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_TASK_TAG_BOLD= IJavaColorConstants.TASK_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD; /** * A named preference that controls whether javadoc keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG; /** * A named preference that controls whether javadoc tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc links. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK; /** * A named preference that controls whether javadoc links are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT; /** * A named preference that controls whether javadoc default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used for 'linked-mode' underline. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$ /** * A named preference that controls whether hover tooltips in the editor are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when no control key is * pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>SHIFT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will be removed in one of the next builds. */ public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>ALT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code>, * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that no hover should be shown for the given key modifiers. * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that the default hover should be shown for the given key * modifiers. The default hover is described by the * <code>EDITOR_DEFAULT_HOVER</code> property. * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$ /** * A named preference that defines the hover named the 'default hover'. * Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$ /** * A named preference that controls if segmented view (show selected element only) is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$ /** * A named preference that controls if browser like links are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 2.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS= "browserLikeLinks"; //$NON-NLS-1$ /** * A named preference that controls the key modifier for browser like links. * <p> * Value is of type <code>String</code>. * </p> * * @since 2.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER= "browserLikeLinksKeyModifier"; //$NON-NLS-1$ /** * A named preference that controls the key modifier mask for browser like links. * The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code> * cannot be resolved to valid SWT modifier bits. * <p> * Value is of type <code>String</code>. * </p> * * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER * @since 2.1.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$ /** * A named preference that controls whether occurrences are marked in the editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_OCCURRENCES= "markOccurrences"; //$NON-NLS-1$ /** * A named preference that controls disabling of the overwrite mode. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_DISABLE_OVERWRITE_MODE= "disable_overwrite_mode"; //$NON-NLS-1$ /** * A named preference that controls the "smart semicolon" smart typing handler * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_SMART_SEMICOLON= "smart_semicolon"; //$NON-NLS-1$ /** * A named preference that controls the "smart opening brace" smart typing handler * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_SMART_OPENING_BRACE= "smart_opening_brace"; //$NON-NLS-1$ /** * A named preference that controls the smart tab behaviour. * <p> * Value is of type <code>Boolean</code>. * * @since 3.0 */ public static final String EDITOR_SMART_TAB= "smart_tab"; //$NON-NLS-1$ /** * A named preference that controls whether code snippets are formatted * in Javadoc comments. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATSOURCE= "comment_format_source_code"; //$NON-NLS-1$ /** * A named preference that controls whether description of Javadoc * parameters are indented. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION= "comment_indent_parameter_description"; //$NON-NLS-1$ /** * A named preference that controls whether the header comment of * a Java source file is formatted. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATHEADER= "comment_format_header"; //$NON-NLS-1$ /** * A named preference that controls whether Javadoc root tags * are indented. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_INDENTROOTTAGS= "comment_indent_root_tags"; //$NON-NLS-1$ /** * A named preference that controls whether Javadoc comments * are formatted by the content formatter. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMAT= "comment_format_comments"; //$NON-NLS-1$ /** * A named preference that controls whether a new line is inserted * after Javadoc root tag parameters. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_NEWLINEFORPARAMETER= "comment_new_line_for_parameter"; //$NON-NLS-1$ /** * A named preference that controls whether an empty line is inserted before * the Javadoc root tag block. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_SEPARATEROOTTAGS= "comment_separate_root_tags"; //$NON-NLS-1$ /** * A named preference that controls whether blank lines are cleared during formatting * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_CLEARBLANKLINES= "comment_clear_blank_lines"; //$NON-NLS-1$ /** * A named preference that controls the line length of comments. * <p> * Value is of type <code>Integer</code>. The value must be at least 4 for reasonable formatting. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_LINELENGTH= "comment_line_length"; //$NON-NLS-1$ /** * A named preference that controls whether html tags are formatted. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATHTML= "comment_format_html"; //$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$ /** * Initializes the given preference store with the default values. * * @param store the preference store to be initialized * * @since 2.1 */ public static void initializeDefaultValues(IPreferenceStore store) { // set the default values from ExtendedTextEditor ExtendedTextEditorPreferenceConstants.initializeDefaultValues(store); store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); // JavaBasePreferencePage store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, false); store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false); store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS); store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING); store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true); // AppearancePreferencePage store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false); store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true); store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$ store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true); // ImportOrganizePreferencePage store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); // ClasspathVariablesPreferencePage // CodeFormatterPreferencePage // CompilerPreferencePage // no initialization needed // RefactoringPreferencePage store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY); store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); // TemplatePreferencePage store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); // CodeGenerationPreferencePage // compatibility code if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) { String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); if (prefix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, prefix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); } } if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) { String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); if (suffix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); } } store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); // MembersOrderPreferencePage store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SI,SF,SM,I,F,C,M"); //$NON-NLS-1$ // must add here to guarantee that it is the first in the listener list store.addPropertyChangeListener(JavaPlugin.getDefault().getMemberOrderPreferenceCache()); // JavaEditorPreferencePage store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192,192)); store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224)); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180)); store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true); store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true); store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200 , 100)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500); store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true); store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false); store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true); store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false); store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true); store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS, false); store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); String mod1Name= Action.findModifierString(SWT.MOD1); // SWT.COMMAND on Mac; SWT.CONTROL elsewhere store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + mod1Name); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + SWT.MOD1); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, true); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, mod1Name); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.MOD1); store.setDefault(PreferenceConstants.EDITOR_SMART_TAB, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMAT, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER, false); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES, false); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHTML, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH, 80); // work in progress WorkInProgressPreferencePage.initDefaults(store); // do more complicated stuff NewJavaProjectPreferencePage.initDefaults(store); } /** * Returns the JDT-UI preference store. * * @return the JDT-UI preference store */ public static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /** * Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>. * * @param description a string value describing the JRE library. The description is used * to indentify the JDR library in the UI * @param entries an array of classpath entries to be encoded * * @return the encoded string. */ public static String encodeJRELibrary(String description, IClasspathEntry[] entries) { return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries); } /** * Decodes an encoded JRE library and returns its description string. * * @return the description of an encoded JRE library * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static String decodeJRELibraryDescription(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); } /** * Decodes an encoded JRE library and returns its classpath entries. * * @return the array of classpath entries of an encoded JRE library. * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); } /** * Returns the current configuration for the JRE to be used as default in new Java projects. * This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST * </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>. * * @return the current default set of classpath entries * * @see #NEWPROJECT_JRELIBRARY_LIST * @see #NEWPROJECT_JRELIBRARY_INDEX */ public static IClasspathEntry[] getDefaultJRELibrary() { return NewJavaProjectPreferencePage.getDefaultJRELibrary(); } }
45,445
Bug 45445 [hovering] No tooltips for local variables
Build 20031023 Hovering over a local variable declaration/reference doesn't show a tooltip. JDT/Core now supports code select on local variable. UI side should be fixed to show the local variable declaration in a tooltip.
resolved fixed
7fdf35b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-28T10:29:37Z
2003-10-23T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavadocHover.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java.hover; import java.io.Reader; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.ui.text.HTMLPrinter; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; /** * Provides Javadoc as hover info for Java elements. * * @since 2.1 */ public class JavadocHover extends AbstractJavaEditorTextHover { private final int LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED | JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS | JavaElementLabels.F_PRE_TYPE_SIGNATURE; /* * @see JavaElementHover */ protected String getHoverInfo(IJavaElement[] result) { StringBuffer buffer= new StringBuffer(); int nResults= result.length; if (nResults > 1) { for (int i= 0; i < result.length; i++) { HTMLPrinter.startBulletList(buffer); IJavaElement curr= result[i]; if (curr instanceof IMember) HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr)); HTMLPrinter.endBulletList(buffer); } } else { IJavaElement curr= result[0]; if (curr instanceof IMember) { IMember member= (IMember) curr; HTMLPrinter.addSmallHeader(buffer, getInfoText(member)); Reader reader; try { reader= JavaDocAccess.getJavaDoc(member, true); } catch (JavaModelException ex) { return null; } if (reader != null) { HTMLPrinter.addParagraph(buffer, new JavaDoc2HTMLTextReader(reader)); } } } if (buffer.length() > 0) { HTMLPrinter.insertPageProlog(buffer, 0); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } return null; } private String getInfoText(IMember member) { return JavaElementLabels.getElementLabel(member, LABEL_FLAGS); } }
45,696
Bug 45696 SIOOBE in org.eclipse.jsp.AbstractJspParser
When I'm using the JSP editor from the Java Family examples, I get a lot of StringIndexOutOfBoundsException in .log : java.lang.StringIndexOutOfBoundsException: String index out of range: 4 at java.lang.String.charAt(String.java:444) at org.eclipse.jsp.AbstractJspParser.parseAttributes(AbstractJspParser.java:154) at org.eclipse.jsp.AbstractJspParser.parseTag(AbstractJspParser.java:87) at org.eclipse.jsp.AbstractJspParser.parse(AbstractJspParser.java:282) at org.eclipse.jsp.JspTranslator.translate(JspTranslator.java:125) at org.eclipse.jdt.internal.ui.examples.jspeditor.Jsp2JavaReconcileStep.reconcileModel(Jsp2JavaReconcileStep.java:76) at org.eclipse.jface.text.reconciler.AbstractReconcileStep.reconcile(AbstractReconcileStep.java:82) at org.eclipse.jdt.internal.ui.examples.jspeditor.JspReconcilingStrategy.reconcile(JspReconcilingStrategy.java:79) at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:76) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:189)
resolved fixed
3227278
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-29T10:13:19Z
2003-10-28T22:26:40Z
org.eclipse.jdt.ui.examples.javafamily/src/org/eclipse/jsp/AbstractJspParser.java
/******************************************************************************* * Copyright (c) 2003 IBM Corporation 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.jsp; import java.io.IOException; import java.io.Reader; public abstract class AbstractJspParser { private Reader fReader; private boolean fHasUnread; private int fUnread; private int fPos; protected int fLines= 1; AbstractJspParser() { super(); } private int getc() throws IOException { fPos++; if (fHasUnread) { fHasUnread= false; return fUnread; } int ch= fReader.read(); if (ch == '\n') // LF fLines++; else if (ch == '\r') { // CR int nextCh= getc(); if (nextCh != '\n') fLines++; return nextCh; } return ch; } private void ungetc(int c) { fHasUnread= true; fUnread= c; fPos--; } private void parseDirective() throws IOException { StringBuffer sb= new StringBuffer(); int pos= fPos; while (true) { int c = getc(); if (c == '%') { c= getc(); if (c == '>') { // get attributes parseAttributes(pos, sb.toString()); return; } } sb.append((char)c); } } private void parseTag(boolean endTag) throws IOException { StringBuffer sb= new StringBuffer(); int pos= fPos; while (true) { int c= getc(); if (c == '/') { c= getc(); if (c == '>') { // get attributes parseAttributes(pos, sb.toString()); return; } else { ungetc(c); } } else if (c == '>') { // get attributes parseAttributes(pos, sb.toString()); return; } sb.append((char)c); } } private void parseComment() throws IOException { while (true) { int c = getc(); if (c == '-') { c= getc(); if (c == '-') { c= getc(); if (c == '%') { c= getc(); if (c == '>') { return; } } } } } } private void parseJava(char type) throws IOException { StringBuffer sb= new StringBuffer(); int line= fLines; while (true) { int c = getc(); if (c == '%') { c= getc(); if (c == '>') { java(type, sb.toString(), line); return; } } sb.append((char)c); } } protected void java(char tagType, String contents, int line) { // empty implementation } private void parseAttributes(int pos, String s) { boolean hasValue= false; StringBuffer name= new StringBuffer(); StringBuffer value= new StringBuffer(); String startTag= ""; //$NON-NLS-1$ int i= 0; int ix= 0; int startName= 0; int startValue= 0; char c= s.charAt(i++); try { while (true) { // whitespace while (Character.isWhitespace(c)) c= s.charAt(i++); startName= i; while (Character.isLetterOrDigit(c) || c == ':') { name.append(c); c= s.charAt(i++); } // whitespace while (Character.isWhitespace(c)) c= s.charAt(i++); hasValue= false; if (c == '=') { c= s.charAt(i++); // value while (Character.isWhitespace(c)) c= s.charAt(i++); startValue= i; // Special handling for this taglib tag if (startTag.equals("c:out")) { //$NON-NLS-1$ value= value.append(s.substring(startValue, Math.max(startValue, s.length() - 2))); name.setLength(0); tagAttribute(name.toString(), value.toString(), startName+pos, startValue+pos); break; } else if (c == '"') { c= s.charAt(i++); while (c != '"') { value.append(c); c= s.charAt(i++); } c= s.charAt(i++); } else { while (Character.isLetterOrDigit(c)) { value.append(c); c= s.charAt(i++); } } hasValue= true; } if (ix == 0) { startTag= name.toString(); startTag(false, startTag, startName+pos); } else tagAttribute(name.toString(), hasValue ? value.toString() : null, startName+pos, startValue+pos); ix++; name.setLength(0); value.setLength(0); } } catch (StringIndexOutOfBoundsException e) { JspUIPlugin.log("error while parsing attributes", e); //$NON-NLS-1$ } if (name.length() > 0) { if (ix == 0) startTag(false, name.toString(), startName+pos); else tagAttribute(name.toString(), hasValue ? value.toString() : null, startName+pos, startValue+pos); } endTag(false); } protected void startTag(boolean endTag, String name, int startName) { // empty implementation } protected void tagAttribute(String attrName, String value, int startName, int startValue) { // empty implementation } protected void endTag(boolean end) { // empty implementation } protected void text(String t, int line) { // empty implementation } void parse(Reader reader) throws IOException { int c; StringBuffer buffer= new StringBuffer(); fPos= 0; fLines= 1; int line= fLines; fReader= reader; while (true) { c= getc(); switch (c) { case -1: if (buffer.length() > 0) text(buffer.toString(), line); return; case '<': c= getc(); if (c == '%') { // flush buffer if (buffer.length() > 0) { text(buffer.toString(), line); buffer.setLength(0); line= fLines; } c= getc(); switch (c) { case '-': c= getc(); if (c == '-') { parseComment(); } else { ungetc(c); continue; } break; case '@': parseDirective(); break; case ' ': case '!': case '=': parseJava((char)c); break; default: parseComment(); break; } } else if (c == '/') { parseTag(true); } else { ungetc(c); parseTag(false); } break; default: buffer.append((char)c); break; } } } }
44,318
Bug 44318 annotation hovers don't show up
...if Preferences-->Java-->Editor-->Annotations-->Analyze annotations while typing is turned off. upon saving/compiling files the yellow and red underlines for warnings and errors show up, but not the hovers.
resolved fixed
3cc3aed
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-30T12:09:53Z
2003-10-07T15:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/AnnotationHover.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java.hover; import java.util.Iterator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.IAnnotationExtension; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation; import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator; import org.eclipse.jdt.internal.ui.text.HTMLPrinter; public class AnnotationHover extends AbstractJavaEditorTextHover { private MarkerAnnotationPreferences fMarkerAnnotationPreferences= new MarkerAnnotationPreferences(); private IPreferenceStore fStore= JavaPlugin.getDefault().getPreferenceStore(); /* * Formats a message as HTML text. */ private String formatMessage(String message) { StringBuffer buffer= new StringBuffer(); HTMLPrinter.addPageProlog(buffer); HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message)); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { if (getEditor() == null) return null; IDocumentProvider provider= JavaPlugin.getDefault().getCompilationUnitDocumentProvider(); IAnnotationModel model= provider.getAnnotationModel(getEditor().getEditorInput()); if (model != null) { Iterator e= new JavaAnnotationIterator(model, true); int layer= -1; String message= null; while (e.hasNext()) { Annotation a= (Annotation) e.next(); if (a instanceof IAnnotationExtension) { AnnotationPreference preference= getAnnotationPreference((IAnnotationExtension)a); if (preference == null || !(fStore.getBoolean(preference.getTextPreferenceKey()) || (preference.getHighlightPreferenceKey() != null && fStore.getBoolean(preference.getHighlightPreferenceKey())))) continue; } Position p= model.getPosition(a); if (a.getLayer() > layer && p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { String msg= ((IJavaAnnotation) a).getMessage(); if (msg != null && msg.trim().length() > 0) { message= msg; layer= a.getLayer(); } } } if (layer > -1) return formatMessage(message); } return null; } /* * @see IJavaEditorTextHover#setEditor(IEditorPart) */ public void setEditor(IEditorPart editor) { if (editor instanceof CompilationUnitEditor) super.setEditor(editor); else super.setEditor(null); } /** * Returns the annotation preference for the given marker. * * @param marker * @return the annotation preference or <code>null</code> if none */ private AnnotationPreference getAnnotationPreference(IAnnotationExtension annotation) { String markerType= annotation.getMarkerType(); int severity= annotation.getSeverity(); Iterator e= fMarkerAnnotationPreferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { AnnotationPreference info= (AnnotationPreference) e.next(); if (info.getMarkerType().equals(markerType) && severity == info.getSeverity()) return info; } return null; } static boolean isJavaProblemHover(String id) { return PreferenceConstants.ID_PROBLEM_HOVER.equals(id); } }
46,042
Bug 46042 [rulers] NPE in preference store, called from JavaAnnotationHover.getJavaAnnotationsForLine
build N20031031 Saw the following in the log. !ENTRY org.eclipse.ui 4 4 Nov 04, 2003 11:17:39.649 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Nov 04, 2003 11:17:39.649 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at java.util.Hashtable.get(Hashtable.java:333) at java.util.Properties.getProperty(Properties.java:563) at org.eclipse.core.runtime.Preferences.getBoolean(Preferences.java:594) at org.eclipse.ui.plugin.AbstractUIPlugin$CompatibilityPreferenceStore.getBoolean (AbstractUIPlugin.java:268) at org.eclipse.jdt.internal.ui.text.JavaAnnotationHover.getJavaAnnotationsForLine (JavaAnnotationHover.java:123) at org.eclipse.jdt.internal.ui.text.JavaAnnotationHover.getHoverInfo (JavaAnnotationHover.java:214) at org.eclipse.jface.text.source.AnnotationBarHoverManager.computeInformation (AnnotationBarHoverManager.java:100) at org.eclipse.jface.text.AbstractInformationControlManager.doShowInformation (AbstractInformationControlManager.java:661) at org.eclipse.jface.text.AbstractHoverInformationControlManager$MouseTracker.mouse Hover(AbstractHoverInformationControlManager.java:298) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:211) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1611) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1594) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
225cfed
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T08:28:43Z
2003-11-04T18:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaAnnotationHover.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationAccess; import org.eclipse.jface.text.source.IAnnotationHover; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; import org.eclipse.ui.texteditor.IAnnotationExtension; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation; /** * Determines all markers for the given line and collects, concatenates, and formates * their messages. */ public class JavaAnnotationHover implements IAnnotationHover { private static class JavaAnnotationHoverType { } public static final JavaAnnotationHoverType OVERVIEW_RULER_HOVER= new JavaAnnotationHoverType(); public static final JavaAnnotationHoverType TEXT_RULER_HOVER= new JavaAnnotationHoverType(); public static final JavaAnnotationHoverType VERTICAL_RULER_HOVER= new JavaAnnotationHoverType(); private MarkerAnnotationPreferences fMarkerAnnotationPreferences= new MarkerAnnotationPreferences(); private IPreferenceStore fStore= JavaPlugin.getDefault().getPreferenceStore(); private IAnnotationAccess fAnnotationAccess= new DefaultMarkerAnnotationAccess(fMarkerAnnotationPreferences); private JavaAnnotationHoverType fType; public JavaAnnotationHover(JavaAnnotationHoverType type) { Assert.isTrue(OVERVIEW_RULER_HOVER.equals(type) || TEXT_RULER_HOVER.equals(type) || VERTICAL_RULER_HOVER.equals(type)); fType= type; } /** * Returns the distance to the ruler line. */ protected int compareRulerLine(Position position, IDocument document, int line) { if (position.getOffset() > -1 && position.getLength() > -1) { try { int javaAnnotationLine= document.getLineOfOffset(position.getOffset()); if (line == javaAnnotationLine) return 1; if (javaAnnotationLine <= line && line <= document.getLineOfOffset(position.getOffset() + position.getLength())) return 2; } catch (BadLocationException x) { } } return 0; } /** * Selects a set of markers from the two lists. By default, it just returns * the set of exact matches. */ protected List select(List exactMatch, List including) { return exactMatch; } /** * Returns one marker which includes the ruler's line of activity. */ protected List getJavaAnnotationsForLine(ISourceViewer viewer, int line) { IDocument document= viewer.getDocument(); IAnnotationModel model= viewer.getAnnotationModel(); if (model == null) return null; List exact= new ArrayList(); List including= new ArrayList(); Iterator e= model.getAnnotationIterator(); HashMap messagesAtPosition= new HashMap(); while (e.hasNext()) { Object o= e.next(); if (o instanceof IJavaAnnotation) { IJavaAnnotation a= (IJavaAnnotation)o; if (OVERVIEW_RULER_HOVER.equals(fType)) { AnnotationPreference preference= getAnnotationPreference(a.getAnnotationType()); if (preference == null || !fStore.getBoolean(preference.getOverviewRulerPreferenceKey())) continue; } else if (TEXT_RULER_HOVER.equals(fType)) { AnnotationPreference preference= getAnnotationPreference(a.getAnnotationType()); if (preference == null || !(fStore.getBoolean(preference.getTextPreferenceKey()) || (preference.getHighlightPreferenceKey() != null && fStore.getBoolean(preference.getHighlightPreferenceKey())))) continue; } else if (VERTICAL_RULER_HOVER.equals(fType)) { AnnotationPreference preference= getAnnotationPreference(a.getAnnotationType()); if (preference == null || !fStore.getBoolean(preference.getVerticalRulerPreferenceKey())) continue; } if (!a.hasOverlay()) { Position position= model.getPosition((Annotation)a); if (position == null) continue; if (isDuplicateJavaAnnotation(messagesAtPosition, position, a.getMessage())) continue; switch (compareRulerLine(position, document, line)) { case 1: exact.add(a); break; case 2: including.add(a); break; } } } else if (o instanceof IAnnotationExtension) { IAnnotationExtension a= (IAnnotationExtension) o; if (OVERVIEW_RULER_HOVER.equals(fType)) { Object type= fAnnotationAccess.getType((Annotation)a); if (type != null) { AnnotationPreference preference= getAnnotationPreference(type.toString()); if (preference == null || !fStore.getBoolean(preference.getOverviewRulerPreferenceKey())) continue; } else continue; } else if (TEXT_RULER_HOVER.equals(fType)) { Object type= fAnnotationAccess.getType((Annotation)a); if (type != null) { AnnotationPreference preference= getAnnotationPreference(type.toString()); if (preference == null || !(fStore.getBoolean(preference.getTextPreferenceKey()) || fStore.getBoolean(preference.getHighlightPreferenceKey()))) continue; } else continue; } else continue; // only take Java annotations for the vertical ruler Position position= model.getPosition((Annotation)a); if (position == null) continue; if (isDuplicateJavaAnnotation(messagesAtPosition, position, a.getMessage())) continue; switch (compareRulerLine(position, document, line)) { case 1: exact.add(a); break; case 2: including.add(a); break; } } } return select(exact, including); } private boolean isDuplicateJavaAnnotation(Map messagesAtPosition, Position position, String message) { if (messagesAtPosition.containsKey(position)) { Object value= messagesAtPosition.get(position); if (message.equals(value)) return true; if (value instanceof List) { List messages= (List)value; if (messages.contains(message)) return true; else messages.add(message); } else { ArrayList messages= new ArrayList(); messages.add(value); messages.add(message); messagesAtPosition.put(position, messages); } } else messagesAtPosition.put(position, message); return false; } /* * @see IVerticalRulerHover#getHoverInfo(ISourceViewer, int) */ public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { List javaAnnotations= getJavaAnnotationsForLine(sourceViewer, lineNumber); if (javaAnnotations != null) { if (javaAnnotations.size() == 1) { // optimization IAnnotationExtension annotation= (IAnnotationExtension) javaAnnotations.get(0); String message= annotation.getMessage(); if (message != null && message.trim().length() > 0) return formatSingleMessage(message); } else { List messages= new ArrayList(); Iterator e= javaAnnotations.iterator(); while (e.hasNext()) { IAnnotationExtension annotation= (IAnnotationExtension) e.next(); String message= annotation.getMessage(); if (message != null && message.trim().length() > 0) messages.add(message.trim()); } if (messages.size() == 1) return formatSingleMessage((String) messages.get(0)); if (messages.size() > 1) return formatMultipleMessages(messages); } } return null; } /* * Formats a message as HTML text. */ private String formatSingleMessage(String message) { StringBuffer buffer= new StringBuffer(); HTMLPrinter.addPageProlog(buffer); HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message)); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } /* * Formats several message as HTML text. */ private String formatMultipleMessages(List messages) { StringBuffer buffer= new StringBuffer(); HTMLPrinter.addPageProlog(buffer); HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(JavaUIMessages.getString("JavaAnnotationHover.multipleMarkersAtThisLine"))); //$NON-NLS-1$ HTMLPrinter.startBulletList(buffer); Iterator e= messages.iterator(); while (e.hasNext()) HTMLPrinter.addBullet(buffer, HTMLPrinter.convertToHTMLContent((String) e.next())); HTMLPrinter.endBulletList(buffer); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } /** * Returns the annotation preference for the given marker. * * @param marker * @return the annotation preference or <code>null</code> if none */ private AnnotationPreference getAnnotationPreference(String annotationType) { Iterator e= fMarkerAnnotationPreferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { AnnotationPreference info= (AnnotationPreference) e.next(); if (info.getAnnotationType().equals(annotationType)) return info; } return null; } }
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/core
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/core
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/core
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
extension/org/eclipse/jdt/internal/corext/template/CodeTemplates.java
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/core
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
extension/org/eclipse/jdt/internal/corext/template/java/CodeTemplateContextType.java
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeTemplateBlock.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.template.CodeTemplates; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateSet; import org.eclipse.jdt.internal.ui.IJavaStatusConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField; /** */ public class CodeTemplateBlock { private class CodeTemplateAdapter implements ITreeListAdapter, IDialogFieldListener { private final Object[] NO_CHILDREN= new Object[0]; public CodeTemplateAdapter(CodeTemplates templates) { } public void customButtonPressed(TreeListDialogField field, int index) { doButtonPressed(index, field.getSelectedElements()); } public void selectionChanged(TreeListDialogField field) { List selected= field.getSelectedElements(); field.enableButton(IDX_EDIT, canEdit(selected)); field.enableButton(IDX_EXPORT, !selected.isEmpty()); updateSourceViewerInput(selected); } public void doubleClicked(TreeListDialogField field) { List selected= field.getSelectedElements(); if (canEdit(selected)) { doButtonPressed(IDX_EDIT, selected); } } public Object[] getChildren(TreeListDialogField field, Object element) { if (element == COMMENT_NODE || element == CODE_NODE) { return getTemplateOfCategory(element == COMMENT_NODE); } return NO_CHILDREN; } public Object getParent(TreeListDialogField field, Object element) { if (element instanceof Template) { Template template= (Template) element; if (template.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) { return COMMENT_NODE; } return CODE_NODE; } return null; } public boolean hasChildren(TreeListDialogField field, Object element) { return (element == COMMENT_NODE || element == CODE_NODE); } public void dialogFieldChanged(DialogField field) { } public void keyPressed(TreeListDialogField field, KeyEvent event) { } } private static class CodeTemplateLabelProvider extends LabelProvider { /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { return null; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { if (element == COMMENT_NODE || element == CODE_NODE) { return (String) element; } Template template = (Template) element; String name= template.getName(); if (CodeTemplates.CATCHBLOCK.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$ } else if (CodeTemplates.METHODSTUB.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$ } else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$ } else if (CodeTemplates.GETTERSTUB.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.getterstub.label"); //$NON-NLS-1$ } else if (CodeTemplates.SETTERSTUB.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.setterstub.label"); //$NON-NLS-1$ } else if (CodeTemplates.NEWTYPE.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$ } else if (CodeTemplates.TYPECOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.METHODCOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.GETTERCOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.gettercomment.label"); //$NON-NLS-1$ } else if (CodeTemplates.SETTERCOMMENT.equals(name)) { return PreferencesMessages.getString("CodeTemplateBlock.settercomment.label"); //$NON-NLS-1$ } return template.getDescription(); } } private final static int IDX_EDIT= 0; private final static int IDX_IMPORT= 2; private final static int IDX_EXPORT= 3; private final static int IDX_EXPORTALL= 4; protected final static Object COMMENT_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$ protected final static Object CODE_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$ private static final String PREF_JAVADOC_STUBS= PreferenceConstants.CODEGEN_ADD_COMMENTS; private TreeListDialogField fCodeTemplateTree; private SelectionButtonDialogField fCreateJavaDocComments; protected CodeTemplates fTemplates; private PixelConverter fPixelConverter; private SourceViewer fPatternViewer; private Control fSWTWidget; public CodeTemplateBlock() { fTemplates= CodeTemplates.getInstance(); CodeTemplateAdapter adapter= new CodeTemplateAdapter(fTemplates); String[] buttonLabels= new String[] { /* IDX_EDIT*/ PreferencesMessages.getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$ /* */ null, /* IDX_IMPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$ /* IDX_EXPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$ /* IDX_EXPORTALL */ PreferencesMessages.getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$ }; fCodeTemplateTree= new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider()); fCodeTemplateTree.setDialogFieldListener(adapter); fCodeTemplateTree.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$ fCodeTemplateTree.enableButton(IDX_EXPORT, false); fCodeTemplateTree.enableButton(IDX_EDIT, false); fCodeTemplateTree.addElement(COMMENT_NODE); fCodeTemplateTree.addElement(CODE_NODE); fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP); fCreateJavaDocComments.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$ fCreateJavaDocComments.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS)); fCodeTemplateTree.selectFirstElement(); } protected Control createContents(Composite parent) { fPixelConverter= new PixelConverter(parent); fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); //layout.marginHeight= 0; //layout.marginWidth= 0; layout.numColumns= 2; composite.setLayout(layout); fCodeTemplateTree.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2); LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null)); fPatternViewer= createViewer(composite, 2); fCreateJavaDocComments.doFillIntoGrid(composite, 2); DialogField label= new DialogField(); label.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.description")); //$NON-NLS-1$ label.doFillIntoGrid(composite, 2); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private SourceViewer createViewer(Composite parent, int nColumns) { Label label= new Label(parent, SWT.NONE); label.setText(PreferencesMessages.getString("CodeTemplateBlock.preview")); //$NON-NLS-1$ GridData data= new GridData(); data.horizontalSpan= nColumns; label.setLayoutData(data); SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); IDocument document= new Document(); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING); viewer.configure(new JavaSourceViewerConfiguration(tools, null, IJavaPartitions.JAVA_PARTITIONING)); viewer.setEditable(false); viewer.setDocument(document); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(viewer, tools); Control control= viewer.getControl(); data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); data.horizontalSpan= nColumns; data.heightHint= fPixelConverter.convertHeightInCharsToPixels(5); control.setLayoutData(data); return viewer; } protected Template[] getTemplateOfCategory(boolean isComment) { ArrayList res= new ArrayList(); Template[] templates= fTemplates.getTemplates(); for (int i= 0; i < templates.length; i++) { Template curr= templates[i]; if (isComment == curr.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) { res.add(curr); } } return (Template[]) res.toArray(new Template[res.size()]); } protected static boolean canEdit(List selected) { return selected.size() == 1 && (selected.get(0) instanceof Template); } protected void updateSourceViewerInput(List selection) { if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) { return; } if (selection.size() == 1 && selection.get(0) instanceof Template) { Template template= (Template) selection.get(0); fPatternViewer.getDocument().set(template.getPattern()); } else { fPatternViewer.getDocument().set(""); //$NON-NLS-1$ } } protected void doButtonPressed(int buttonIndex, List selected) { if (buttonIndex == IDX_EDIT) { edit((Template) selected.get(0)); } else if (buttonIndex == IDX_EXPORT) { export(selected); } else if (buttonIndex == IDX_EXPORTALL) { exportAll(); } else if (buttonIndex == IDX_IMPORT) { import_(); } } private void edit(Template template) { Template newTemplate= new Template(template); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, false, new String[0]); if (dialog.open() == Window.OK) { // changed template.setDescription(newTemplate.getDescription()); template.setPattern(newTemplate.getPattern()); fCodeTemplateTree.refresh(template); fCodeTemplateTree.selectElements(new StructuredSelection(template)); } } private void import_() { FileDialog dialog= new FileDialog(getShell()); dialog.setText(PreferencesMessages.getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.import.extension")}); //$NON-NLS-1$ String path= dialog.open(); if (path != null) { try { fTemplates.addFromFile(new File(path), false); } catch (CoreException e) { openReadErrorDialog(e); } fCodeTemplateTree.refresh(); } } private void exportAll() { export(fTemplates); } private void export(List selected) { TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag()); for (int i= 0; i < selected.size(); i++) { Object curr= selected.get(i); if (curr instanceof Template) { addToTemplateSet(templateSet, (Template) curr); } else { Template[] templates= getTemplateOfCategory(curr == COMMENT_NODE); for (int k= 0; k < templates.length; k++) { addToTemplateSet(templateSet, templates[k]); } } } export(templateSet); } private void addToTemplateSet(TemplateSet set, Template template) { if (set.getFirstTemplate(template.getName()) == null) { set.add(template); } } private void export(TemplateSet templateSet) { FileDialog dialog= new FileDialog(getShell(), SWT.SAVE); dialog.setText(PreferencesMessages.getFormattedString("CodeTemplateBlock.export.title", String.valueOf(templateSet.getTemplates().length))); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.export.extension")}); //$NON-NLS-1$ dialog.setFileName(PreferencesMessages.getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; File file= new File(path); if (file.isHidden()) { String title= PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } if (file.exists() && !file.canWrite()) { String title= PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } if (!file.exists() || confirmOverwrite(file)) { try { templateSet.saveToFile(file); } catch (CoreException e) { if (e.getStatus().getException() instanceof FileNotFoundException) { String title= PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.fileNotFound", e.getStatus().getException().getLocalizedMessage()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } JavaPlugin.log(e); openWriteErrorDialog(e); } } } private boolean confirmOverwrite(File file) { return MessageDialog.openQuestion(getShell(), PreferencesMessages.getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$ PreferencesMessages.getFormattedString("CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ } public void performDefaults() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS)); try { fTemplates.restoreDefaults(); } catch (CoreException e) { JavaPlugin.log(e); openReadErrorDialog(e); } // refresh fCodeTemplateTree.refresh(); } public boolean performOk(boolean enabled) { IPreferenceStore prefs= PreferenceConstants.getPreferenceStore(); prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected()); JavaPlugin.getDefault().savePluginPreferences(); try { fTemplates.save(); } catch (CoreException e) { JavaPlugin.log(e); openWriteErrorDialog(e); } return true; } public void performCancel() { try { fTemplates.reset(); } catch (CoreException e) { openReadErrorDialog(e); } } private void openReadErrorDialog(CoreException e) { String title= PreferencesMessages.getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$ // Show parse error in a user dialog without logging if (e.getStatus().getCode() == IJavaStatusConstants.TEMPLATE_PARSE_EXCEPTION) { String message= e.getStatus().getException().getLocalizedMessage(); if (message != null) message= PreferencesMessages.getFormattedString("CodeTemplateBlock.error.parse.message", message); //$NON-NLS-1$ else message= PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); } else { String message= PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } } private void openWriteErrorDialog(CoreException e) { String title= PreferencesMessages.getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } }
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/EditTemplateDialog.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.PreferenceConstants; 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.corext.template.ContextType; import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplateVariable; 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.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; import org.eclipse.jdt.internal.ui.text.template.TemplateVariableProcessor; import org.eclipse.jdt.internal.ui.util.SWTUtil; /** * Dialog to edit a template. */ public class EditTemplateDialog extends StatusDialog { private static class SimpleJavaSourceViewerConfiguration extends JavaSourceViewerConfiguration { private final TemplateVariableProcessor fProcessor; SimpleJavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, TemplateVariableProcessor processor) { super(tools, editor, IJavaPartitions.JAVA_PARTITIONING); fProcessor= processor; } /* * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); IColorManager manager= textTools.getColorManager(); ContentAssistant assistant= new ContentAssistant(); assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE); // Register the same processor for strings and single line comments to get code completion at the start of those partitions. assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_STRING); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_CHARACTER); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_MULTI_LINE_COMMENT); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_DOC); assistant.enableAutoInsert(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT)); assistant.enableAutoActivation(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION)); assistant.setAutoActivationDelay(store.getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); Color background= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); assistant.setContextInformationPopupBackground(background); assistant.setContextSelectorBackground(background); assistant.setProposalSelectorBackground(background); Color foreground= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); assistant.setContextInformationPopupForeground(foreground); assistant.setContextSelectorForeground(foreground); assistant.setProposalSelectorForeground(foreground); return assistant; } private Color getColor(IPreferenceStore store, String key, IColorManager manager) { RGB rgb= PreferenceConverter.getColor(store, key); return manager.getColor(rgb); } /* * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) * @since 2.1 */ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) { return new TemplateVariableTextHover(fProcessor); } } private static class TemplateVariableTextHover implements ITextHover { private TemplateVariableProcessor fProcessor; /** * @param type */ public TemplateVariableTextHover(TemplateVariableProcessor processor) { fProcessor= processor; } /* (non-Javadoc) * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion subject) { try { IDocument doc= textViewer.getDocument(); int offset= subject.getOffset(); if (offset >= 2 && "${".equals(doc.get(offset-2, 2))) { //$NON-NLS-1$ String varName= doc.get(offset, subject.getLength()); Iterator iter= fProcessor.getContextType().variableIterator(); while (iter.hasNext()) { TemplateVariable var= (TemplateVariable) iter.next(); if (varName.equals(var.getName())) { return var.getDescription(); } } } } catch (BadLocationException e) { } return null; } /* (non-Javadoc) * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { if (textViewer != null) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } return null; } } private static class TextViewerAction extends Action implements IUpdate { private int fOperationCode= -1; private ITextOperationTarget fOperationTarget; public TextViewerAction(ITextViewer viewer, int operationCode) { fOperationCode= operationCode; fOperationTarget= viewer.getTextOperationTarget(); update(); } /** * Updates the enabled state of the action. * Fires a property change if the enabled state changes. * * @see Action#firePropertyChange(String, Object, Object) */ public void update() { boolean wasEnabled= isEnabled(); boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); setEnabled(isEnabled); if (wasEnabled != isEnabled) { firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE); } } /** * @see Action#run() */ public void run() { if (fOperationCode != -1 && fOperationTarget != null) { fOperationTarget.doOperation(fOperationCode); } } } private final Template fTemplate; private Text fNameText; private Text fDescriptionText; private Combo fContextCombo; private SourceViewer fPatternEditor; private Button fInsertVariableButton; private boolean fIsNameModifiable; private StatusInfo fValidationStatus; private boolean fSuppressError= true; // #4354 private Map fGlobalActions= new HashMap(10); private List fSelectionActions = new ArrayList(3); private String[] fContextTypes; private final TemplateVariableProcessor fTemplateProcessor= new TemplateVariableProcessor(); public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, String[] contextTypes) { super(parent); setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE); String title= edit ? TemplateMessages.getString("EditTemplateDialog.title.edit") //$NON-NLS-1$ : TemplateMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$ setTitle(title); fTemplate= template; fIsNameModifiable= isNameModifiable; fContextTypes= contextTypes; fValidationStatus= new StatusInfo(); ContextType type= ContextTypeRegistry.getInstance().getContextType(template.getContextTypeName()); fTemplateProcessor.setContextType(type); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite ancestor) { Composite parent= new Composite(ancestor, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; parent.setLayout(layout); parent.setLayoutData(new GridData(GridData.FILL_BOTH)); ModifyListener listener= new ModifyListener() { public void modifyText(ModifyEvent e) { doTextWidgetChanged(e.widget); } }; if (fIsNameModifiable) { createLabel(parent, TemplateMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$ Composite composite= new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layout= new GridLayout(); layout.numColumns= 3; layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); fNameText= createText(composite); fNameText.addModifyListener(listener); createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$ fContextCombo= new Combo(composite, SWT.READ_ONLY); for (int i= 0; i < fContextTypes.length; i++) { fContextCombo.add(fContextTypes[i]); } fContextCombo.addModifyListener(listener); } createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$ int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY; fDescriptionText= new Text(parent, descFlags ); fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fDescriptionText.addModifyListener(listener); Label patternLabel= createLabel(parent, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); fPatternEditor= createEditor(parent); Label filler= new Label(parent, SWT.NONE); filler.setLayoutData(new GridData()); Composite composite= new Composite(parent, SWT.NONE); layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); composite.setLayoutData(new GridData()); fInsertVariableButton= new Button(composite, SWT.NONE); fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton)); fInsertVariableButton.setText(TemplateMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ fInsertVariableButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { fPatternEditor.getTextWidget().setFocus(); fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); } public void widgetDefaultSelected(SelectionEvent e) {} }); fDescriptionText.setText(fTemplate.getDescription()); if (fIsNameModifiable) { fNameText.setText(fTemplate.getName()); fContextCombo.select(getIndex(fTemplate.getContextTypeName())); } else { fPatternEditor.getControl().setFocus(); } initializeActions(); applyDialogFont(parent); return composite; } protected void doTextWidgetChanged(Widget w) { if (w == fNameText) { String name= fNameText.getText(); if (fSuppressError && (name.trim().length() != 0)) fSuppressError= false; fTemplate.setName(name); updateButtons(); } else if (w == fContextCombo) { String name= fContextCombo.getText(); fTemplate.setContext(name); fTemplateProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType(name)); } else if (w == fDescriptionText) { String desc= fDescriptionText.getText(); fTemplate.setDescription(desc); } } protected void doSourceChanged(IDocument document) { String text= document.get(); fTemplate.setPattern(text); fValidationStatus.setOK(); ContextType contextType= ContextTypeRegistry.getInstance().getContextType(fTemplate.getContextTypeName()); if (contextType != null) { try { String errorMessage= contextType.validate(text); if (errorMessage != null) { fValidationStatus.setError(errorMessage); } } catch (CoreException e) { JavaPlugin.log(e); } } updateUndoAction(); updateButtons(); } private static GridData getButtonGridData(Button button) { GridData data= new GridData(GridData.FILL_HORIZONTAL); data.heightHint= SWTUtil.getButtonHeightHint(button); return data; } private static Label createLabel(Composite parent, String name) { Label label= new Label(parent, SWT.NULL); label.setText(name); label.setLayoutData(new GridData()); return label; } private static Text createText(Composite parent) { Text text= new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return text; } private SourceViewer createEditor(Composite parent) { SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); IDocument document= new Document(fTemplate.getPattern()); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING); viewer.configure(new SimpleJavaSourceViewerConfiguration(tools, null, fTemplateProcessor)); viewer.setEditable(true); viewer.setDocument(document); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(viewer, tools); int nLines= document.getNumberOfLines(); if (nLines < 5) { nLines= 5; } else if (nLines > 12) { nLines= 12; } Control control= viewer.getControl(); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(80); data.heightHint= convertHeightInCharsToPixels(nLines); control.setLayoutData(data); viewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { if (event .getDocumentEvent() != null) doSourceChanged(event.getDocumentEvent().getDocument()); } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateSelectionDependentActions(); } }); if (viewer instanceof ITextViewerExtension) { ((ITextViewerExtension) viewer).prependVerifyKeyListener(new VerifyKeyListener() { public void verifyKey(VerifyEvent event) { handleVerifyKeyPressed(event); } }); } else { viewer.getTextWidget().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } public void keyReleased(KeyEvent e) {} }); } return viewer; } private void handleKeyPressed(KeyEvent event) { if (event.stateMask != SWT.MOD1) return; switch (event.character) { case ' ': fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); break; // CTRL-Z case 'z' - 'a' + 1: fPatternEditor.doOperation(ITextOperationTarget.UNDO); break; } } private void handleVerifyKeyPressed(VerifyEvent event) { if (!event.doit) return; if (event.stateMask != SWT.MOD1) return; switch (event.character) { case ' ': fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); event.doit= false; break; // CTRL-Z case 'z' - 'a' + 1: fPatternEditor.doOperation(ITextOperationTarget.UNDO); event.doit= false; break; } } private void initializeActions() { TextViewerAction action= new TextViewerAction(fPatternEditor, SourceViewer.UNDO); action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.UNDO, action); action= new TextViewerAction(fPatternEditor, SourceViewer.CUT); action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.CUT, action); action= new TextViewerAction(fPatternEditor, SourceViewer.COPY); action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.COPY, action); action= new TextViewerAction(fPatternEditor, SourceViewer.PASTE); action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.PASTE, action); action= new TextViewerAction(fPatternEditor, SourceViewer.SELECT_ALL); action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); action= new TextViewerAction(fPatternEditor, SourceViewer.CONTENTASSIST_PROPOSALS); action.setText(TemplateMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$ fSelectionActions.add(ITextEditorActionConstants.CUT); fSelectionActions.add(ITextEditorActionConstants.COPY); fSelectionActions.add(ITextEditorActionConstants.PASTE); // create context menu MenuManager manager= new MenuManager(null, null); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { fillContextMenu(mgr); } }); StyledText text= fPatternEditor.getTextWidget(); Menu menu= manager.createContextMenu(text); text.setMenu(menu); } private void fillContextMenu(IMenuManager menu) { menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ } protected void updateSelectionDependentActions() { Iterator iterator= fSelectionActions.iterator(); while (iterator.hasNext()) updateAction((String)iterator.next()); } protected void updateUndoAction() { IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO); if (action instanceof IUpdate) ((IUpdate) action).update(); } protected void updateAction(String actionId) { IAction action= (IAction) fGlobalActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } private int getIndex(String context) { ContextTypeRegistry registry= ContextTypeRegistry.getInstance(); registry.getContextType(context); if (context == null) return -1; for (int i= 0; i < fContextTypes.length; i++) { if (context.equals(fContextTypes[i])) { return i; } } return -1; } protected void okPressed() { super.okPressed(); } private void updateButtons() { StatusInfo status; boolean valid= fNameText == null || fNameText.getText().trim().length() != 0; if (!valid) { status = new StatusInfo(); if (!fSuppressError) { status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ } } else { status= fValidationStatus; } updateStatus(status); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG); } }
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TemplatePreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.Window; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplateSet; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContextType; import org.eclipse.jdt.internal.corext.template.java.JavaDocContextType; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.IJavaStatusConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.template.TemplateContentProvider; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.SWTUtil; public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { Template template = (Template) element; switch (columnIndex) { case 0: return template.getName(); case 1: return template.getContextTypeName(); case 2: return template.getDescription(); default: return ""; //$NON-NLS-1$ } } } // preference store keys private static final String PREF_FORMAT_TEMPLATES= PreferenceConstants.TEMPLATES_USE_CODEFORMATTER; private final String[] CONTEXTS= new String[] { JavaContextType.NAME, JavaDocContextType.NAME }; private Templates fTemplates; private CheckboxTableViewer fTableViewer; private Button fAddButton; private Button fEditButton; private Button fImportButton; private Button fExportButton; private Button fExportAllButton; private Button fRemoveButton; private Button fEnableAllButton; private Button fDisableAllButton; private SourceViewer fPatternViewer; private Button fFormatButton; public TemplatePreferencePage() { super(); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(TemplateMessages.getString("TemplatePreferencePage.message")); //$NON-NLS-1$ fTemplates= Templates.getInstance(); } /* * (non-Javadoc) * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.TEMPLATE_PREFERENCE_PAGE); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite ancestor) { Composite parent= new Composite(ancestor, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; parent.setLayout(layout); Composite innerParent= new Composite(parent, SWT.NONE); GridLayout innerLayout= new GridLayout(); innerLayout.numColumns= 2; innerLayout.marginHeight= 0; innerLayout.marginWidth= 0; innerParent.setLayout(innerLayout); GridData gd= new GridData(GridData.FILL_BOTH); gd.horizontalSpan= 2; innerParent.setLayoutData(gd); Table table= new Table(innerParent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(3); data.heightHint= convertHeightInCharsToPixels(10); table.setLayoutData(data); table.setHeaderVisible(true); table.setLinesVisible(true); TableLayout tableLayout= new TableLayout(); table.setLayout(tableLayout); TableColumn column1= new TableColumn(table, SWT.NONE); column1.setText(TemplateMessages.getString("TemplatePreferencePage.column.name")); //$NON-NLS-1$ TableColumn column2= new TableColumn(table, SWT.NONE); column2.setText(TemplateMessages.getString("TemplatePreferencePage.column.context")); //$NON-NLS-1$ TableColumn column3= new TableColumn(table, SWT.NONE); column3.setText(TemplateMessages.getString("TemplatePreferencePage.column.description")); //$NON-NLS-1$ fTableViewer= new CheckboxTableViewer(table); fTableViewer.setLabelProvider(new TemplateLabelProvider()); fTableViewer.setContentProvider(new TemplateContentProvider()); fTableViewer.setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object object1, Object object2) { if ((object1 instanceof Template) && (object2 instanceof Template)) { Template left= (Template) object1; Template right= (Template) object2; int result= left.getName().compareToIgnoreCase(right.getName()); if (result != 0) return result; return left.getDescription().compareToIgnoreCase(right.getDescription()); } return super.compare(viewer, object1, object2); } public boolean isSorterProperty(Object element, String property) { return true; } }); fTableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent e) { edit(); } }); fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent e) { selectionChanged1(); } }); fTableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { Template template= (Template) event.getElement(); template.setEnabled(event.getChecked()); } }); Composite buttons= new Composite(innerParent, SWT.NONE); buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; buttons.setLayout(layout); fAddButton= new Button(buttons, SWT.PUSH); fAddButton.setText(TemplateMessages.getString("TemplatePreferencePage.new")); //$NON-NLS-1$ fAddButton.setLayoutData(getButtonGridData(fAddButton)); fAddButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { add(); } }); fEditButton= new Button(buttons, SWT.PUSH); fEditButton.setText(TemplateMessages.getString("TemplatePreferencePage.edit")); //$NON-NLS-1$ fEditButton.setLayoutData(getButtonGridData(fEditButton)); fEditButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { edit(); } }); fRemoveButton= new Button(buttons, SWT.PUSH); fRemoveButton.setText(TemplateMessages.getString("TemplatePreferencePage.remove")); //$NON-NLS-1$ fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton)); fRemoveButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { remove(); } }); fImportButton= new Button(buttons, SWT.PUSH); fImportButton.setText(TemplateMessages.getString("TemplatePreferencePage.import")); //$NON-NLS-1$ fImportButton.setLayoutData(getButtonGridData(fImportButton)); fImportButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { import_(); } }); fExportButton= new Button(buttons, SWT.PUSH); fExportButton.setText(TemplateMessages.getString("TemplatePreferencePage.export")); //$NON-NLS-1$ fExportButton.setLayoutData(getButtonGridData(fExportButton)); fExportButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { export(); } }); fExportAllButton= new Button(buttons, SWT.PUSH); fExportAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.export.all")); //$NON-NLS-1$ fExportAllButton.setLayoutData(getButtonGridData(fExportAllButton)); fExportAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { exportAll(); } }); fEnableAllButton= new Button(buttons, SWT.PUSH); fEnableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.enable.all")); //$NON-NLS-1$ fEnableAllButton.setLayoutData(getButtonGridData(fEnableAllButton)); fEnableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { enableAll(true); } }); fDisableAllButton= new Button(buttons, SWT.PUSH); fDisableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.disable.all")); //$NON-NLS-1$ fDisableAllButton.setLayoutData(getButtonGridData(fDisableAllButton)); fDisableAllButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { enableAll(false); } }); fPatternViewer= createViewer(parent); fFormatButton= new Button(parent, SWT.CHECK); fFormatButton.setText(TemplateMessages.getString("TemplatePreferencePage.use.code.formatter")); //$NON-NLS-1$ GridData gd1= new GridData(); gd1.horizontalSpan= 2; fFormatButton.setLayoutData(gd1); fTableViewer.setInput(fTemplates); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fFormatButton.setSelection(prefs.getBoolean(PREF_FORMAT_TEMPLATES)); updateButtons(); configureTableResizing(innerParent, buttons, table, column1, column2, column3); Dialog.applyDialogFont(parent); return parent; } /** * Correctly resizes the table so no phantom columns appear */ private static void configureTableResizing(final Composite parent, final Composite buttons, final Table table, final TableColumn column1, final TableColumn column2, final TableColumn column3) { parent.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { Rectangle area= parent.getClientArea(); Point preferredSize= table.computeSize(SWT.DEFAULT, SWT.DEFAULT); int width= area.width - 2 * table.getBorderWidth(); if (preferredSize.y > area.height) { // Subtract the scrollbar width from the total column width // if a vertical scrollbar will be required Point vBarSize = table.getVerticalBar().getSize(); width -= vBarSize.x; } width -= buttons.getSize().x; Point oldSize= table.getSize(); if (oldSize.x > width) { // table is getting smaller so make the columns // smaller first and then resize the table to // match the client area width column1.setWidth(width/4); column2.setWidth(width/4); column3.setWidth(width - (column1.getWidth() + column2.getWidth())); table.setSize(width, area.height); } else { // table is getting bigger so make the table // bigger first and then make the columns wider // to match the client area width table.setSize(width, area.height); column1.setWidth(width / 4); column2.setWidth(width / 4); column3.setWidth(width - (column1.getWidth() + column2.getWidth())); } } }); } private Template[] getEnabledTemplates() { Template[] templates= fTemplates.getTemplates(); List list= new ArrayList(templates.length); for (int i= 0; i != templates.length; i++) if (templates[i].isEnabled()) list.add(templates[i]); return (Template[]) list.toArray(new Template[list.size()]); } private SourceViewer createViewer(Composite parent) { Label label= new Label(parent, SWT.NONE); label.setText(TemplateMessages.getString("TemplatePreferencePage.preview")); //$NON-NLS-1$ GridData data= new GridData(); data.horizontalSpan= 2; label.setLayoutData(data); SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); IDocument document= new Document(); tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING); viewer.configure(new JavaSourceViewerConfiguration(tools, null, IJavaPartitions.JAVA_PARTITIONING)); viewer.setEditable(false); viewer.setDocument(document); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(viewer, tools); Control control= viewer.getControl(); data= new GridData(GridData.FILL_BOTH); data.horizontalSpan= 2; data.heightHint= convertHeightInCharsToPixels(5); control.setLayoutData(data); return viewer; } private static GridData getButtonGridData(Button button) { GridData data= new GridData(GridData.FILL_HORIZONTAL); data.widthHint= SWTUtil.getButtonWidthHint(button); data.heightHint= SWTUtil.getButtonHeightHint(button); return data; } private void selectionChanged1() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); if (selection.size() == 1) { Template template= (Template) selection.getFirstElement(); fPatternViewer.getDocument().set(template.getPattern()); } else { fPatternViewer.getDocument().set(""); //$NON-NLS-1$ } updateButtons(); } private void updateButtons() { int selectionCount= ((IStructuredSelection) fTableViewer.getSelection()).size(); int itemCount= fTableViewer.getTable().getItemCount(); fEditButton.setEnabled(selectionCount == 1); fExportButton.setEnabled(selectionCount > 0); fRemoveButton.setEnabled(selectionCount > 0 && selectionCount <= itemCount); fEnableAllButton.setEnabled(itemCount > 0); fDisableAllButton.setEnabled(itemCount > 0); } private void add() { Template template= new Template(); template.setContext(CONTEXTS[0]); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, false, true, CONTEXTS); if (dialog.open() == Window.OK) { fTemplates.add(template); fTableViewer.refresh(); fTableViewer.setChecked(template, template.isEnabled()); fTableViewer.setSelection(new StructuredSelection(template)); } } private void edit() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Object[] objects= selection.toArray(); if ((objects == null) || (objects.length != 1)) return; Template template= (Template) selection.getFirstElement(); edit(template); } private void edit(Template template) { Template newTemplate= new Template(template); EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, true, CONTEXTS); if (dialog.open() == Window.OK) { if (!newTemplate.getName().equals(template.getName()) && MessageDialog.openQuestion(getShell(), TemplateMessages.getString("TemplatePreferencePage.question.create.new.title"), //$NON-NLS-1$ TemplateMessages.getString("TemplatePreferencePage.question.create.new.message"))) //$NON-NLS-1$ { template= newTemplate; fTemplates.add(template); fTableViewer.refresh(); } else { template.setName(newTemplate.getName()); template.setDescription(newTemplate.getDescription()); template.setContext(newTemplate.getContextTypeName()); template.setPattern(newTemplate.getPattern()); fTableViewer.refresh(template); } fTableViewer.setChecked(template, template.isEnabled()); fTableViewer.setSelection(new StructuredSelection(template)); } } private void import_() { FileDialog dialog= new FileDialog(getShell()); dialog.setText(TemplateMessages.getString("TemplatePreferencePage.import.title")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.import.extension")}); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; try { fTemplates.addFromFile(new File(path), true); fTableViewer.refresh(); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); } catch (CoreException e) { openReadErrorDialog(e); } } private void exportAll() { export(fTemplates); } private void export() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Object[] templates= selection.toArray(); TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag()); for (int i= 0; i != templates.length; i++) templateSet.add((Template) templates[i]); export(templateSet); } private void export(TemplateSet templateSet) { FileDialog dialog= new FileDialog(getShell(), SWT.SAVE); dialog.setText(TemplateMessages.getFormattedString("TemplatePreferencePage.export.title", new Integer(templateSet.getTemplates().length))); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.export.extension")}); //$NON-NLS-1$ dialog.setFileName(TemplateMessages.getString("TemplatePreferencePage.export.filename")); //$NON-NLS-1$ String path= dialog.open(); if (path == null) return; File file= new File(path); if (file.isHidden()) { String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$ String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } if (file.exists() && !file.canWrite()) { String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$ String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } if (!file.exists() || confirmOverwrite(file)) { try { templateSet.saveToFile(file); } catch (CoreException e) { if (e.getStatus().getException() instanceof FileNotFoundException) { String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$ String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.fileNotFound", e.getStatus().getException().getLocalizedMessage()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); return; } JavaPlugin.log(e); openWriteErrorDialog(e); } } } private boolean confirmOverwrite(File file) { return MessageDialog.openQuestion(getShell(), TemplateMessages.getString("TemplatePreferencePage.export.exists.title"), //$NON-NLS-1$ TemplateMessages.getFormattedString("TemplatePreferencePage.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ } private void remove() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); Iterator elements= selection.iterator(); while (elements.hasNext()) { Template template= (Template) elements.next(); fTemplates.remove(template); } fTableViewer.refresh(); } private void enableAll(boolean enable) { Template[] templates= fTemplates.getTemplates(); for (int i= 0; i != templates.length; i++) templates[i].setEnabled(enable); fTableViewer.setAllChecked(enable); } /* * @see IWorkbenchPreferencePage#init(IWorkbench) */ public void init(IWorkbench workbench) {} /* * @see Control#setVisible(boolean) */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) setTitle(TemplateMessages.getString("TemplatePreferencePage.title")); //$NON-NLS-1$ } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fFormatButton.setSelection(prefs.getDefaultBoolean(PREF_FORMAT_TEMPLATES)); try { fTemplates.restoreDefaults(); } catch (CoreException e) { openReadErrorDialog(e); } // refresh fTableViewer.refresh(); fTableViewer.setAllChecked(false); fTableViewer.setCheckedElements(getEnabledTemplates()); } /* * @see PreferencePage#performOk() */ public boolean performOk() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); prefs.setValue(PREF_FORMAT_TEMPLATES, fFormatButton.getSelection()); try { fTemplates.save(); } catch (CoreException e) { JavaPlugin.log(e); openWriteErrorDialog(e); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /* * @see PreferencePage#performCancel() */ public boolean performCancel() { try { fTemplates.reset(); } catch (CoreException e) { openReadErrorDialog(e); } return super.performCancel(); } private void openReadErrorDialog(CoreException e) { String title= TemplateMessages.getString("TemplatePreferencePage.error.read.title"); //$NON-NLS-1$ // Show parse error in a user dialog without logging if (e.getStatus().getCode() == IJavaStatusConstants.TEMPLATE_PARSE_EXCEPTION) { String message= e.getStatus().getException().getLocalizedMessage(); if (message != null) message= TemplateMessages.getFormattedString("TemplatePreferencePage.error.parse.message", message); //$NON-NLS-1$ else message= TemplateMessages.getString("TemplatePreferencePage.error.read.message"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); } else { String message= TemplateMessages.getString("TemplatePreferencePage.error.read.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } } private void openWriteErrorDialog(CoreException e) { ErrorDialog.openError(getShell(), TemplateMessages.getString("TemplatePreferencePage.error.write.title"), //$NON-NLS-1$ null, e.getStatus()); } }
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavadocTagsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.text.edits.InsertEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.ui.CodeGeneration; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess; import org.eclipse.jdt.internal.corext.javadoc.JavaDocTag; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.ui.JavaPluginImages; /** * */ public class JavadocTagsSubProcessor { public static void getMissingJavadocCommentProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ASTNode node= problem.getCoveringNode(context.getASTRoot()); if (node == null) { return; } BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node); if (declaration == null) { return; } ICompilationUnit cu= context.getCompilationUnit(); ITypeBinding binding= Bindings.getBindingOfParentType(declaration); if (binding == null) { return; } if (declaration instanceof MethodDeclaration) { MethodDeclaration methodDecl= (MethodDeclaration) declaration; IMethodBinding methodBinding= methodDecl.resolveBinding(); if (methodBinding != null) { methodBinding= Bindings.findDeclarationInHierarchy(binding, methodBinding.getName(), methodBinding.getParameterTypes()); } String string= CodeGeneration.getMethodComment(cu, binding.getName(), methodDecl, methodBinding, String.valueOf('\n')); if (string != null) { String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.method.description"); //$NON-NLS-1$ proposals.add(getNewJavadocTagProposal(cu, declaration.getStartPosition(), string, label)); } } else if (declaration instanceof TypeDeclaration) { String typeQualifiedName= Bindings.getTypeQualifiedName(binding); String string= CodeGeneration.getTypeComment(cu, typeQualifiedName, String.valueOf('\n')); if (string != null) { String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.type.description"); //$NON-NLS-1$ proposals.add(getNewJavadocTagProposal(cu, declaration.getStartPosition(), string, label)); } } else if (declaration instanceof FieldDeclaration) { String comment= "/**\n *\n */\n"; //$NON-NLS-1$ String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.field.description"); //$NON-NLS-1$ proposals.add(getNewJavadocTagProposal(cu, declaration.getStartPosition(), comment, label)); } } private static CUCorrectionProposal getNewJavadocTagProposal(ICompilationUnit cu, int insertPosition, String comment, String label) throws CoreException { Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG); CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 1, image); TextBuffer buffer= TextBuffer.acquire((IFile) cu.getResource()); try { int tabWidth= CodeFormatterUtil.getTabWidth(); int line= buffer.getLineOfOffset(insertPosition); String lineContent= buffer.getLineContent(line); String indentString= Strings.getIndentString(lineContent, tabWidth); String str= Strings.changeIndent(comment, 0, tabWidth, indentString, buffer.getLineDelimiter()); TextEdit rootEdit= proposal.getRootTextEdit(); InsertEdit edit= new InsertEdit(insertPosition, str); rootEdit.addChild(edit); //$NON-NLS-1$ if (comment.charAt(comment.length() - 1) != '\n') { rootEdit.addChild(new InsertEdit(insertPosition, buffer.getLineDelimiter())); rootEdit.addChild(new InsertEdit(insertPosition, indentString)); } return proposal; } finally { TextBuffer.release(buffer); } } public static void getMissingJavadocTagProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ASTNode node= problem.getCoveringNode(context.getASTRoot()); if (node == null) { return; } BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node); if (!(declaration instanceof MethodDeclaration)) { return; } Javadoc javadoc= declaration.getJavadoc(); if (javadoc == null) { return; } MethodDeclaration methodDecl= (MethodDeclaration) declaration; Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG); JavadocRewriteProposal proposal= new JavadocRewriteProposal("", context.getCompilationUnit(), javadoc, 1, image); //$NON-NLS-1$ JavaDocTag[] existingTags= proposal.getTags(); switch (problem.getProblemId()) { case IProblem.AnnotationMissingParamTag: { String name= ASTNodes.asString(node); proposal.setDisplayName(CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.paramtag.description")); //$NON-NLS-1$ int insertPosition= findParamInsertPosition(existingTags, methodDecl, node.getParent()); proposal.insertNewTag(insertPosition, new JavaDocTag(JavaDocTag.PARAM, name)); break; } case IProblem.AnnotationMissingReturnTag: { proposal.setDisplayName(CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.returntag.description")); //$NON-NLS-1$ int insertPosition= findReturnInsertPosition(existingTags); proposal.insertNewTag(insertPosition, new JavaDocTag(JavaDocTag.RETURN, "")); //$NON-NLS-1$ break; } case IProblem.AnnotationMissingThrowsTag: { String name= ASTNodes.asString(node); proposal.setDisplayName(CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.throwstag.description")); //$NON-NLS-1$ int insertPosition= findThrowsInsertPosition(existingTags, methodDecl, node); proposal.insertNewTag(insertPosition, new JavaDocTag(JavaDocTag.THROWS, name)); break; } default: return; } proposals.add(proposal); String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.allmissing.description"); //$NON-NLS-1$ JavadocRewriteProposal addAllMissing= new JavadocRewriteProposal(label, context.getCompilationUnit(), javadoc, 5, image); //$NON-NLS-1$ List list= methodDecl.parameters(); for (int i= 0; i < list.size(); i++) { SingleVariableDeclaration decl= (SingleVariableDeclaration) list.get(i); String name= decl.getName().getIdentifier(); if (findTag(existingTags, JavaDocTag.PARAM, name) == null) { int insertPosition= findParamInsertPosition(existingTags, methodDecl, decl); addAllMissing.insertNewTag(insertPosition, new JavaDocTag(JavaDocTag.PARAM, name)); //$NON-NLS-1$ } } if (!methodDecl.isConstructor()) { Type type= methodDecl.getReturnType(); if (!type.isPrimitiveType() || (((PrimitiveType) type).getPrimitiveTypeCode() != PrimitiveType.VOID)) { if (findTag(existingTags, JavaDocTag.RETURN, null) == null) { int insertPosition= findReturnInsertPosition(existingTags); addAllMissing.insertNewTag(insertPosition, new JavaDocTag(JavaDocTag.RETURN, "")); //$NON-NLS-1$ } } } List throwsExceptions= methodDecl.thrownExceptions(); for (int i= 0; i < throwsExceptions.size(); i++) { Name exception= (Name) throwsExceptions.get(i); ITypeBinding binding= exception.resolveTypeBinding(); if (binding != null) { String name= binding.getName(); if (findThrowsTag(existingTags, name) == null) { int insertPosition= findThrowsInsertPosition(existingTags, methodDecl, exception); addAllMissing.insertNewTag(insertPosition, new JavaDocTag(JavaDocTag.THROWS, name)); //$NON-NLS-1$ } } } proposals.add(addAllMissing); } private static JavaDocTag findTag(JavaDocTag[] existingTags, String name, String arg) { for (int i= 0; i < existingTags.length; i++) { JavaDocTag curr= existingTags[i]; if (name.equals(curr.getName())) { if (arg != null) { String argument= getArgument(curr.getContent()); if (argument.equals(arg)) { return curr; } } else { return curr; } } } return null; } private static JavaDocTag findThrowsTag(JavaDocTag[] existingTags, String arg) { for (int i= 0; i < existingTags.length; i++) { JavaDocTag curr= existingTags[i]; String currName= curr.getName(); if (JavaDocTag.THROWS.equals(currName) || JavaDocTag.EXCEPTION.equals(currName)) { String argument= getArgument(curr.getContent()); if (argument.equals(arg) || (Signature.getSimpleName(argument)).equals(arg)) { return curr; } } } return null; } private static int findThrowsInsertPosition(JavaDocTag[] tags, MethodDeclaration methodDecl, ASTNode node) { Set previousArgs= new HashSet(); List list= methodDecl.thrownExceptions(); for (int i= 0; i < list.size() && node != list.get(i); i++) { Name curr= (Name) list.get(i); previousArgs.add(ASTResolving.getSimpleName(curr)); } int lastThrows= tags.length; for (int i= tags.length - 1; i >= 0; i--) { JavaDocTag curr= tags[i]; if (JavaDocTag.THROWS.equals(curr.getName())) { String arg= getArgument(curr.getContent()); if (previousArgs.contains(arg) || previousArgs.contains(Signature.getSimpleName(arg))) { return i + 1; } lastThrows= i; } } return lastThrows; } private static int findReturnInsertPosition(JavaDocTag[] tags) { int res= tags.length; for (int i= tags.length - 1; i >= 0; i--) { JavaDocTag curr= tags[i]; if (JavaDocTag.THROWS.equals(curr.getName())) { res= i; } else if (JavaDocTag.PARAM.equals(curr.getName())) { return i + 1; } } return res; } private static int findParamInsertPosition(JavaDocTag[] tags, MethodDeclaration methodDecl, ASTNode node) { Set previousArgs= new HashSet(); List list= methodDecl.parameters(); for (int i= 0; i < list.size() && (list.get(i) != node); i++) { SingleVariableDeclaration curr= (SingleVariableDeclaration) list.get(i); previousArgs.add(curr.getName().getIdentifier()); } for (int i= tags.length - 1; i >= 0; i--) { JavaDocTag curr= tags[i]; if (JavaDocTag.PARAM.equals(curr.getName())) { String arg= getArgument(curr.getContent()); if (previousArgs.contains(arg)) { return i + 1; } } } if (tags.length > 0 && tags[0].getName() == null) { return 1; } return 0; } private static String getArgument(String content) { int i= 0; while (i < content.length() && !Character.isWhitespace(content.charAt(i))) { i++; } return content.substring(0, i); } private static class JavadocRewriteProposal extends CUCorrectionProposal { private static class Event { JavaDocTag originalTag; JavaDocTag newTag; public Event(JavaDocTag originalTag, JavaDocTag newTag) { this.originalTag= originalTag; this.newTag= newTag; } public boolean isInserted() { return originalTag == null && newTag != null; } public boolean isRemoved() { return originalTag != null && newTag == null; } } private Javadoc fJavadoc; private JavaDocTag[] fOriginalTags; private List fChangedList; public JavadocRewriteProposal(String name, ICompilationUnit cu, Javadoc javadoc, int relevance, Image image) throws JavaModelException { super(name, cu, relevance, image); fJavadoc= javadoc; fOriginalTags= JavaDocAccess.getJavaDocTags(cu, javadoc.getStartPosition(), javadoc.getLength()); fChangedList= new ArrayList(); for (int i= 0; i < fOriginalTags.length; i++) { JavaDocTag curr= fOriginalTags[i]; fChangedList.add(new Event(curr, curr)); } } public JavaDocTag[] getTags() { return fOriginalTags; } public void insertNewTag(int index, JavaDocTag tag) { if (index < 0 || index > fOriginalTags.length) { throw new IllegalArgumentException(); } int count= 0; // insert after all other previously insted tags int insertPos; for (insertPos= 0; insertPos < fChangedList.size(); insertPos++) { Event curr= (Event) fChangedList.get(insertPos); if (!curr.isInserted()) { if (count == index) { break; } count++; } } fChangedList.add(insertPos, new Event(null, tag)); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#createCompilationUnitChange(String, ICompilationUnit, TextEdit) */ protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException { CompilationUnitChange change= super.createCompilationUnitChange(name, cu, rootEdit); TextBuffer buffer= null; try { buffer= TextBuffer.acquire(change.getFile()); createEdits(buffer, cu, rootEdit); } finally { if (buffer != null) { TextBuffer.release(buffer); } } return change; } /* private void createEditsNew(TextBuffer buffer, ICompilationUnit cu, TextEdit root) throws JavaModelException { IBuffer cuBuffer= cu.getBuffer(); String comment= cuBuffer.getText(fJavadoc.getStartPosition(), fJavadoc.getLength()); try { String cat= "cat"; //$NON-NLS-1$ Document doc= new Document(comment); doc.addPositionCategory(cat); int offset= fJavadoc.getStartPosition(); int currPos= 3; for (int i= fChangedList.size() - 1; i > 0; i--) { Event curr= (Event) fChangedList.get(i); JavaDocTag origTag= curr.originalTag; JavaDocTag newTag= curr.newTag; if (origTag == newTag) { int start= origTag.getOffset(); int end= origTag.getContentOffset() + origTag.getContentLength(); doc.addPosition(cat, new Position(start - offset, end - start)); currPos= origTag.getOffset() + origTag.getLength() - offset; } else if (newTag == null) { // remove doc.replace(origTag.getOffset() - offset, origTag.getLength(), ""); //$NON-NLS-1$ currPos= origTag.getOffset() + origTag.getLength() - offset; } else if (origTag == null) { // insert String string= getNewTagString(curr.newTag); doc.replace(currPos, 0, string); } else { // replace String string= getNewTagString(curr.newTag); doc.replace(origTag.getOffset() - offset, origTag.getLength(), string); //$NON-NLS-1$ } } Position[] positions= doc.getPositions(cat); String str= doc.get(); System.out.println(str); System.out.println("++++++++"); //$NON-NLS-1$ for (int i= 0; i < positions.length; i++) { Position pos= positions[i]; String string= doc.get(pos.getOffset(), pos.getLength()); System.out.println(string); } } catch (BadLocationException e) { } catch (BadPositionCategoryException e) { } }*/ private void createEdits(TextBuffer buffer, ICompilationUnit cu, TextEdit root) { //createEditsNew(buffer, cu, root); int currPos= fJavadoc.getStartPosition() + 3; boolean needsLead= true; boolean isLast= false; for (int i= 0; i < fChangedList.size(); i++) { Event curr= (Event) fChangedList.get(i); if (curr.isInserted()) { StringBuffer buf= new StringBuffer(); if (needsLead) { buf.append('\n'); } buf.append(getNewTagString(curr.newTag)); if (!needsLead && !isLast) { buf.append('\n'); } String indentString= getIndent(buffer) + " * "; //$NON-NLS-1$ String str= Strings.changeIndent(buf.toString(), 0, CodeFormatterUtil.getTabWidth(), indentString, buffer.getLineDelimiter()); if (isLast) { str= "* " + str + buffer.getLineDelimiter() + getIndent(buffer) + ' ';//$NON-NLS-1$ } root.addChild(new InsertEdit(currPos, str)); } else { JavaDocTag original= curr.originalTag; currPos= original.getOffset() + original.getLength(); needsLead= false; isLast= (fOriginalTags.length > 0 && fOriginalTags[fOriginalTags.length - 1] == original); } } } private String getNewTagString(JavaDocTag newTag) { StringBuffer buf= new StringBuffer(); if (newTag.getName() != null) { buf.append('@'); buf.append(newTag.getName()); if (newTag.getContent().length() > 0) { buf.append(' '); } } buf.append(newTag.getContent()); return buf.toString(); } private String getIndent(TextBuffer buffer) { String line= buffer.getLineContentOfOffset(fJavadoc.getStartPosition()); String indent= Strings.getIndentString(line, CodeFormatterUtil.getTabWidth()); return indent; } } }
45,517
Bug 45517 Add a 'Field comment' code template
20031024 The user should be able to specify a 'field comment' template. See 'CodeTemplateContextType.TYPE_COMMENT' as an example You have to - define a new variable type - specify the variables avaiable in this template - create an API in Codetemplates so it can be used Users are: - AddJavadocCommentAction - JavadocTagsSubProcessor.getMissingJavadocCommentProposals
resolved fixed
8309e79
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:33:54Z
2003-10-24T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/CodeGeneration.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; /** * Class that offers access to the templates contained in the 'code generation' preference page. * * @since 2.1 */ public class CodeGeneration { private CodeGeneration() { } /** * Returns the content for a new compilation unit using the 'new Java file' code template. * @param cu The compilation to create the source for. The compilation unit does not need to exist. * @param typeComment The comment for the type to created. Used when the code template contains a ${typecomment} variable. Can be <code>null</code> if * no comment should be added. * @param typeContent The code of the type, including type declaration and body. * @param lineDelimiter The line delimiter to be used. * @return Returns the new content or <code>null</code> if the template is undefined or empty. * @throws CoreException */ public static String getCompilationUnitContent(ICompilationUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException { return StubUtility.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter); } /** * Returns the content for a new type comment using the 'typecomment' code template. The returned content is unformatted and is not indented. * @param cu The compilation where the type is contained. The compilation unit does not need to exist. * @param typeQualifiedName The name of the type to which the comment is added. For inner types the name must be qualified and include the outer * types names (dot separated). See {@link org.eclipse.jdt.core.IType#getTypeQualifiedName(char)}. * @param lineDelimiter The line delimiter to be used. * @return Returns the new content or <code>null</code> if the code template is undefined or empty. The returned content is unformatted and is not indented. * @throws CoreException */ public static String getTypeComment(ICompilationUnit cu, String typeQualifiedName, String lineDelimiter) throws CoreException { return StubUtility.getTypeComment(cu, typeQualifiedName, lineDelimiter); } /** * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). * <code>null</code> is returned if the template is empty. * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer * types names (dot separated). See {@link org.eclipse.jdt.core.IType#getTypeQualifiedName(char)} * @param decl The MethodDeclaration AST node that will be added as new * method. The node does not need to exist in an AST (no parent needed) and does not need to resolve. * See {@link org.eclipse.jdt.core.dom.AST#newMethodDeclaration()} fo how to create such a node. * @param overridden The binding of the method that will be overridden by the created * method or <code>null</code> if no method is overridden. * @param lineDelimiter The line delimiter to be used. * @return Returns the generated method comment or <code>null</code> if the * code template is empty. The returned content is unformatted and not indented (formatting required). * @throws CoreException */ public static String getMethodComment(ICompilationUnit cu, String declaringTypeName, MethodDeclaration decl, IMethodBinding overridden, String lineDelimiter) throws CoreException { return StubUtility.getMethodComment(cu, declaringTypeName, decl, overridden, lineDelimiter); } /** * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). * <code>null</code> is returned if the template is empty. * <p>The returned string is unformatted and not indented. * <p>Exception types and return type are in signature notation. e.g. a source method declared as <code>public void foo(String text, int length)</code> * would return the array <code>{"QString;","I"}</code> as parameter types. See {@link org.eclipse.jdt.core.Signature} * * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer * types names (dot separated). * @param methodName Name of the method. * @param paramNames Names of the parameters for the method. * @param excTypeSig Throwns exceptions (Signature notation) * @param retTypeSig Return type (Signature notation) or <code>null</code> * for constructors. * @param overridden The method that will be overridden by the created method or * <code>null</code> for non-overriding methods. If not <code>null</code>, the method must exist. * @param lineDelimiter The line delimiter to be used * @return Returns the constructed comment or <code>null</code> if * the comment code template is empty. The returned content is unformatted and not indented (formatting required). * @throws CoreException */ public static String getMethodComment(ICompilationUnit cu, String declaringTypeName, String methodName, String[] paramNames, String[] excTypeSig, String retTypeSig, IMethod overridden, String lineDelimiter) throws CoreException { return StubUtility.getMethodComment(cu, declaringTypeName, methodName, paramNames, excTypeSig, retTypeSig, overridden, lineDelimiter); } /** * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). * <code>null</code> is returned if the template is empty. * <p>The returned string is unformatted and not indented. * * @param method The method to be documented. The method must exist. * @param overridden The method that will be overridden by the created method or * <code>null</code> for non-overriding methods. If not <code>null</code>, the method must exist. * @param lineDelimiter The line delimiter to be used * @return Returns the constructed comment or <code>null</code> if * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). * @throws CoreException */ public static String getMethodComment(IMethod method, IMethod overridden, String lineDelimiter) throws CoreException { return StubUtility.getMethodComment(method, overridden, lineDelimiter); } /** * Returns the content of body for a method or constructor using the method body templates. * <code>null</code> is returned if the template is empty. * <p>The returned string is unformatted and not indented. * * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer * types names (dot separated). * @param methodName Name of the method. * @param isConstructor Defines if the created body is for a constructor * @param bodyStatement The code to be entered at the place of the variable ${body_statement}. * @return Returns the constructed body contnet or <code>null</code> if * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). * @throws CoreException */ public static String getMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, boolean isConstructor, String bodyStatement, String lineDelimiter) throws CoreException { return StubUtility.getMethodBodyContent(isConstructor, cu.getJavaProject(), declaringTypeName, methodName, bodyStatement, lineDelimiter); } /** * Returns the content of body for a getter method using the getter method body template. * <code>null</code> is returned if the template is empty. * <p>The returned string is unformatted and not indented. * * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer * types names (dot separated). * @param methodName The name of the getter method. * @param fieldName The name of the field to be set in the setter method, corresponding to the template variable for ${field}. * @return Returns the constructed body content or <code>null</code> if * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). * @throws CoreException */ public static String getGetterMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String lineDelimiter) throws CoreException { return StubUtility.getGetterMethodBodyContent(cu.getJavaProject(), declaringTypeName, methodName, fieldName, lineDelimiter); } /** * Returns the content of body for a setter method using the setter method body template. * <code>null</code> is returned if the template is empty. * <p>The returned string is unformatted and not indented. * * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer * types names (dot separated). * @param methodName The name of the setter method. * @param fieldName The name of the field to be set in the setter method, corresponding to the template variable for ${field}. * @param fieldType The type of the field that is to set, corresponding to the template variable for ${field_type}. * @param paramName The parameter passed to the setter method, corresponding to the template variable for $(param). * @return Returns the constructed body content or <code>null</code> if * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). * @throws CoreException */ public static String getSetterMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String paramName, String lineDelimiter) throws CoreException { return StubUtility.getSetterMethodBodyContent(cu.getJavaProject(), declaringTypeName, methodName, fieldName, paramName, lineDelimiter); } /** * Returns the comment for a getter method using the getter comment template. * <code>null</code> is returned if the template is empty. * <p>The returned string is unformatted and not indented. * * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer * types names (dot separated). See {@link org.eclipse.jdt.core.IType#getTypeQualifiedName(char)} * @param methodName Name of the method. * @param fieldName name of the field that is get. * @param fieldType The type of the field that is to get. * @param bareFieldName The field name without prefix or suffix. * @param lineDelimiter The line delimiter to be used. * @return Returns the generated getter comment or <code>null</code> if the * code template is empty. The returned content is not indented. * @throws CoreException * @since 3.0 */ public static String getGetterComment(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String bareFieldName, String lineDelimiter) throws CoreException { return StubUtility.getGetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, bareFieldName, lineDelimiter); } /** * Returns the comment for a setter method using the setter method body template. * <code>null</code> is returned if the template is empty. * <p>The returned string is unformatted and not indented. * * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer * types names (dot separated). See {@link org.eclipse.jdt.core.IType#getTypeQualifiedName(char)} * @param methodName Name of the method. * @param fieldName name of the field that is set. * @param fieldType The type of the field that is to set. * @param paramName The name of the parameter that is set. * @param bareFieldName The field name without prefix or suffix. * @param lineDelimiter The line delimiter to be used. * @return Returns the generated setter comment or <code>null</code> if the * code template is empty. The returned comment is not indented. * @throws CoreException * @since 3.0 */ public static String getSetterComment(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter) throws CoreException { return StubUtility.getSetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, paramName, bareFieldName, lineDelimiter); } }
43,003
Bug 43003 Disable warning/don't show again checkbox
When I reorder the contents of a source file using 'Source -> Sort Members' I get given a warning box that says task tags will be lost, click OK to continue. Whilst this is a useful warning to show the first time this occurs, it would really be great to be able to disable the warning so that it does not occur each time I am trying to work with code. A preferences checkbox showing disabled warnings, or even using the new 'Error/Warn/Ignore' for Java compile issues could be used so that the warning wasn't shown again, and/or a checkbox on the dialog saying 'Do not show this warning again'. NB the dialog of course only appears in files that have task markers, which I usually have in the form of a // TODO marker when I see this problem. Mac OS X.2.6/Eclipse 3.0M3
verified fixed
5b6bf54
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T14:45:52Z
2003-09-12T09:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SortMembersAction.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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 java.lang.reflect.InvocationTargetException; import java.util.Iterator; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.codemanipulation.SortMembersOperation; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.ActionUtil; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.util.ElementValidator; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Sorts the members of a compilation unit with the sort order as specified in * the Sort Order preference page. * <p> * The action will open the parent compilation unit in a Java editor. The result * is unsaved, so the user can decide if the changes are acceptable. * <p> * The action is applicable to structured selections containing a single * <code>ICompilationUnit</code> or top level <code>IType</code> in a * compilation unit. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.1 */ public class SortMembersAction extends SelectionDispatchAction { private CompilationUnitEditor fEditor; /** * Creates a new <code>SortMembersAction</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 SortMembersAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("SortMembersAction.label")); //$NON-NLS-1$ setDescription(ActionMessages.getString("SortMembersAction.description")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("SortMembersAction.tooltip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.SORT_MEMBERS_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public SortMembersAction(CompilationUnitEditor editor) { this(editor.getEditorSite()); fEditor= editor; setEnabled(checkEnabledEditor()); } private boolean checkEnabledEditor() { return fEditor != null && SelectionConverter.canOperateOn(fEditor); } //---- Structured Viewer ----------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void selectionChanged(IStructuredSelection selection) { boolean enabled= false; try { enabled= getSelectedCompilationUnit(selection) != null; } catch (JavaModelException e) { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 if (JavaModelUtil.filterNotPresentException(e)) JavaPlugin.log(e); } setEnabled(enabled); } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void run(IStructuredSelection selection) { Shell shell= getShell(); try { ICompilationUnit cu= getSelectedCompilationUnit(selection); int cuMembers= cu.getTypes().length; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38496 IType type= cu.findPrimaryType(); int memberCount= type.getChildren().length; if (cuMembers <= 1 && memberCount <= 1) { MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("SortMembersAction.no_members")); //$NON-NLS-1$ return; } if (cu == null || !ElementValidator.check(cu, getShell(), getDialogTitle(), false)) { return; } // open an editor and work on a working copy IEditorPart editor= EditorUtility.openInEditor(cu); if (editor != null) { run(shell, JavaModelUtil.toWorkingCopy(cu), editor); } } catch (CoreException e) { ExceptionHandler.handle(e, shell, getDialogTitle(), null); } } //---- Java Editior -------------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void selectionChanged(ITextSelection selection) { } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void run(ITextSelection selection) { Shell shell= getShell(); IJavaElement input= SelectionConverter.getInput(fEditor); if (input instanceof ICompilationUnit) { if (ElementValidator.check(input, getShell(), getDialogTitle(), true)) { run(shell, (ICompilationUnit) input, fEditor); } } else { MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("SortMembersAction.not_applicable")); //$NON-NLS-1$ } } //---- Helpers ------------------------------------------------------------------- private boolean containsRelevantMarkers(IEditorPart editor) { IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); Iterator iterator= model.getAnnotationIterator(); while (iterator.hasNext()) { Object element= iterator.next(); if (element instanceof IJavaAnnotation) { IJavaAnnotation annot= (IJavaAnnotation) element; if (annot.isRelevant() && !annot.isTemporary() && !annot.isProblem()) return true; } } return false; } private void run(Shell shell, ICompilationUnit cu, IEditorPart editor) { if (!ActionUtil.isProcessable(getShell(), cu)) { return; } if (containsRelevantMarkers(editor)) { if (!MessageDialog.openConfirm(getShell(), getDialogTitle(), ActionMessages.getString("SortMembersAction.containsmarkers"))) { //$NON-NLS-1$ return; } } SortMembersOperation op= new SortMembersOperation(cu, null); try { BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext(); context.run(false, true, new WorkbenchRunnableAdapter(op)); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, shell, getDialogTitle(), null); } catch (InterruptedException e) { // Do nothing. Operation has been canceled by user. } } private ICompilationUnit getSelectedCompilationUnit(IStructuredSelection selection) throws JavaModelException { if (selection.size() == 1) { Object element= selection.getFirstElement(); if (element instanceof ICompilationUnit) { return (ICompilationUnit) element; } else if (element instanceof IType) { IType type= (IType) element; if (type.getParent() instanceof ICompilationUnit) { // only top level types return type.getCompilationUnit(); } } } return null; } private String getDialogTitle() { return ActionMessages.getString("SortMembersAction.error.title"); //$NON-NLS-1$ } }
41,851
Bug 41851 code generation pref page: layout makes it hard to find two checkboxes [code manipulation]
20030820 the 2 checkboxes on the code gen pref page are located at the bottom of the page and very easily missed when you see the page. they should be made more prominent.
resolved fixed
1eb4c1d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T15:46:12Z
2003-08-22T11:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NameConventionConfigurationBlock.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IStatus; 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.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.ColumnLayoutData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /* * The page to configure name conventions */ public class NameConventionConfigurationBlock extends OptionsConfigurationBlock { private final static int FIELD= 1; private final static int STATIC= 2; private final static int ARGUMENT= 3; private final static int LOCAL= 4; // Preference store keys, see JavaCore.getOptions private static final String PREF_FIELD_PREFIXES= JavaCore.CODEASSIST_FIELD_PREFIXES; private static final String PREF_FIELD_SUFFIXES= JavaCore.CODEASSIST_FIELD_SUFFIXES; private static final String PREF_STATIC_FIELD_PREFIXES= JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES; private static final String PREF_STATIC_FIELD_SUFFIXES= JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES; private static final String PREF_ARGUMENT_PREFIXES= JavaCore.CODEASSIST_ARGUMENT_PREFIXES; private static final String PREF_ARGUMENT_SUFFIXES= JavaCore.CODEASSIST_ARGUMENT_SUFFIXES; private static final String PREF_LOCAL_PREFIXES= JavaCore.CODEASSIST_LOCAL_PREFIXES; private static final String PREF_LOCAL_SUFFIXES= JavaCore.CODEASSIST_LOCAL_SUFFIXES; private static class NameConventionEntry { public int kind; public String prefix; public String suffix; public String prefixkey; public String suffixkey; } private class NameConventionInputDialog extends StatusDialog implements IDialogFieldListener { private StringDialogField fPrefixField; private StringDialogField fSuffixField; private NameConventionEntry fEntry; private DialogField fMessageField; public NameConventionInputDialog(Shell parent, String title, String message, NameConventionEntry entry) { super(parent); fEntry= entry; setTitle(title); fMessageField= new DialogField(); fMessageField.setLabelText(message); fPrefixField= new StringDialogField(); fPrefixField.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.dialog.prefix")); //$NON-NLS-1$ fPrefixField.setDialogFieldListener(this); fSuffixField= new StringDialogField(); fSuffixField.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.dialog.suffix")); //$NON-NLS-1$ fSuffixField.setDialogFieldListener(this); fPrefixField.setText(entry.prefix); fSuffixField.setText(entry.suffix); } public NameConventionEntry getResult() { NameConventionEntry res= new NameConventionEntry(); res.prefix= fPrefixField.getText(); res.suffix= fSuffixField.getText(); res.prefixkey= fEntry.prefixkey; res.suffixkey= fEntry.suffixkey; res.kind= fEntry.kind; return res; } protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; inner.setLayout(layout); fMessageField.doFillIntoGrid(inner, 2); fPrefixField.doFillIntoGrid(inner, 2); fSuffixField.doFillIntoGrid(inner, 2); LayoutUtil.setHorizontalGrabbing(fPrefixField.getTextControl(null)); LayoutUtil.setWidthHint(fPrefixField.getTextControl(null), convertWidthInCharsToPixels(45)); LayoutUtil.setWidthHint(fSuffixField.getTextControl(null), convertWidthInCharsToPixels(45)); fPrefixField.postSetFocusOnDialogField(parent.getDisplay()); applyDialogFont(composite); return composite; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField) */ public void dialogFieldChanged(DialogField field) { // validate IStatus prefixStatus= validateIdentifiers(getTokens(fPrefixField.getText(), ","), true); //$NON-NLS-1$ IStatus suffixStatus= validateIdentifiers(getTokens(fSuffixField.getText(), ","), false); //$NON-NLS-1$ updateStatus(StatusUtil.getMoreSevere(suffixStatus, prefixStatus)); } private IStatus validateIdentifiers(String[] values, boolean prefix) { for (int i= 0; i < values.length; i++) { String val= values[i]; if (val.length() == 0) { if (prefix) { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("NameConventionConfigurationBlock.error.emptyprefix")); //$NON-NLS-1$ } else { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("NameConventionConfigurationBlock.error.emptysuffix")); //$NON-NLS-1$ } } String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$ IStatus status= JavaConventions.validateFieldName(name); if (status.matches(IStatus.ERROR)) { if (prefix) { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("NameConventionConfigurationBlock.error.invalidprefix", val)); //$NON-NLS-1$ } else { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("NameConventionConfigurationBlock.error.invalidsuffix", val)); //$NON-NLS-1$ } } } return new StatusInfo(); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); //WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.IMPORT_ORGANIZE_INPUT_DIALOG); } } private static class NameConventionLabelProvider extends LabelProvider implements ITableLabelProvider { /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { return getColumnImage(element, 0); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { return getColumnText(element, 0); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) */ public Image getColumnImage(Object element, int columnIndex) { if (columnIndex != 0) { return null; } NameConventionEntry entry= (NameConventionEntry) element; ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry(); switch (entry.kind) { case FIELD: return registry.get(JavaPluginImages.DESC_FIELD_PUBLIC); case STATIC: return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_FIELD_PUBLIC, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE)); case ARGUMENT: return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE); default: return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE); } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) */ public String getColumnText(Object element, int columnIndex) { NameConventionEntry entry= (NameConventionEntry) element; if (columnIndex == 0) { switch (entry.kind) { case FIELD: return PreferencesMessages.getString("NameConventionConfigurationBlock.field.label"); //$NON-NLS-1$ case STATIC: return PreferencesMessages.getString("NameConventionConfigurationBlock.static.label"); //$NON-NLS-1$ case ARGUMENT: return PreferencesMessages.getString("NameConventionConfigurationBlock.arg.label"); //$NON-NLS-1$ default: return PreferencesMessages.getString("NameConventionConfigurationBlock.local.label"); //$NON-NLS-1$ } } else if (columnIndex == 1) { return entry.prefix; } else { return entry.suffix; } } } private class NameConventionAdapter implements IListAdapter, IDialogFieldListener { private boolean canEdit(ListDialogField field) { return field.getSelectedElements().size() == 1; } public void customButtonPressed(ListDialogField field, int index) { doEditButtonPressed(); } public void selectionChanged(ListDialogField field) { field.enableButton(0, canEdit(field)); } public void doubleClicked(ListDialogField field) { if (canEdit(field)) { doEditButtonPressed(); } } public void dialogFieldChanged(DialogField field) { validateSettings(null, null); } } private ListDialogField fNameConventionList; private SelectionButtonDialogField fUseKeywordThisBox; private SelectionButtonDialogField fUseIsForBooleanGettersBox; private static final String PREF_KEYWORD_THIS= PreferenceConstants.CODEGEN_KEYWORD_THIS; private static final String PREF_IS_FOR_GETTERS= PreferenceConstants.CODEGEN_IS_FOR_GETTERS; public NameConventionConfigurationBlock(IStatusChangeListener context, IJavaProject project) { super(context, project); NameConventionAdapter adapter= new NameConventionAdapter(); String[] buttons= new String[] { /* 0 */ PreferencesMessages.getString("NameConventionConfigurationBlock.list.edit.button") //$NON-NLS-1$ }; fNameConventionList= new ListDialogField(adapter, buttons, new NameConventionLabelProvider()); fNameConventionList.setDialogFieldListener(adapter); fNameConventionList.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.list.label")); //$NON-NLS-1$ String[] columnsHeaders= new String[] { PreferencesMessages.getString("NameConventionConfigurationBlock.list.name.column"), //$NON-NLS-1$ PreferencesMessages.getString("NameConventionConfigurationBlock.list.prefix.column"), //$NON-NLS-1$ PreferencesMessages.getString("NameConventionConfigurationBlock.list.suffix.column"), //$NON-NLS-1$ }; ColumnLayoutData[] data= new ColumnLayoutData[] { new ColumnWeightData(3), new ColumnWeightData(2), new ColumnWeightData(2) }; fNameConventionList.setTableColumns(new ListDialogField.ColumnsDescription(data, columnsHeaders, true)); unpackEntries(); if (fNameConventionList.getSize() > 0) { fNameConventionList.selectFirstElement(); } else { fNameConventionList.enableButton(0, false); } // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38879 fUseKeywordThisBox= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP); fUseKeywordThisBox.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.keywordthis.label")); //$NON-NLS-1$ fUseKeywordThisBox.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_KEYWORD_THIS)); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=39044 fUseIsForBooleanGettersBox= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP); fUseIsForBooleanGettersBox.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.isforbooleangetters.label")); //$NON-NLS-1$ fUseIsForBooleanGettersBox.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_IS_FOR_GETTERS)); } protected String[] getAllKeys() { return new String[] { PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES, PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES }; } protected Control createContents(Composite parent) { setShell(parent.getShell()); GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite composite= new Composite(parent, SWT.NONE); composite.setLayout(layout); fNameConventionList.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fNameConventionList.getLabelControl(null), 2); Table table= fNameConventionList.getTableViewer().getTable(); GridData data= (GridData)fNameConventionList.getListControl(null).getLayoutData(); data.grabExcessHorizontalSpace= true; data.verticalAlignment= 0; data.heightHint= SWTUtil.getTableHeightHint(table, 5); fUseKeywordThisBox.doFillIntoGrid(composite, 2); fUseIsForBooleanGettersBox.doFillIntoGrid(composite, 2); return composite; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String) */ protected void validateSettings(String changedKey, String newValue) { // no validation } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls() */ protected void updateControls() { unpackEntries(); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean) */ protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { return null; // no build required } private void createEntry(List list, String prefixKey, String suffixKey, int kind) { NameConventionEntry entry= new NameConventionEntry(); entry.kind= kind; entry.suffixkey= suffixKey; entry.prefixkey= prefixKey; entry.suffix= (String) fWorkingValues.get(suffixKey); entry.prefix= (String) fWorkingValues.get(prefixKey); list.add(entry); } private void unpackEntries() { ArrayList list= new ArrayList(4); createEntry(list, PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, FIELD); createEntry(list, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES, STATIC); createEntry(list, PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, ARGUMENT); createEntry(list, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES, LOCAL); fNameConventionList.setElements(list); } private void packEntries() { for (int i= 0; i < fNameConventionList.getSize(); i++) { NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getElement(i); fWorkingValues.put(entry.suffixkey, entry.suffix); fWorkingValues.put(entry.prefixkey, entry.prefix); } } private void doEditButtonPressed() { NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getSelectedElements().get(0); String title; String message; switch (entry.kind) { case FIELD: title= PreferencesMessages.getString("NameConventionConfigurationBlock.field.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.field.dialog.message"); //$NON-NLS-1$ break; case STATIC: title= PreferencesMessages.getString("NameConventionConfigurationBlock.static.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.static.dialog.message"); //$NON-NLS-1$ break; case ARGUMENT: title= PreferencesMessages.getString("NameConventionConfigurationBlock.arg.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.arg.dialog.message"); //$NON-NLS-1$ break; default: title= PreferencesMessages.getString("NameConventionConfigurationBlock.local.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.local.dialog.message"); //$NON-NLS-1$ } NameConventionInputDialog dialog= new NameConventionInputDialog(getShell(), title, message, entry); if (dialog.open() == Window.OK) { fNameConventionList.replaceElement(entry, dialog.getResult()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performDefaults() */ public void performDefaults() { super.performDefaults(); IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fUseKeywordThisBox.setSelection(prefs.getDefaultBoolean(PREF_KEYWORD_THIS)); fUseIsForBooleanGettersBox.setSelection(prefs.getDefaultBoolean(PREF_IS_FOR_GETTERS)); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performOk(boolean) */ public boolean performOk(boolean enabled) { IPreferenceStore prefs= PreferenceConstants.getPreferenceStore(); prefs.setValue(PREF_KEYWORD_THIS, fUseKeywordThisBox.isSelected()); prefs.setValue(PREF_IS_FOR_GETTERS, fUseIsForBooleanGettersBox.isSelected()); JavaPlugin.getDefault().savePluginPreferences(); packEntries(); return super.performOk(enabled); } }
46,074
Bug 46074 JUnit launcher: new API in VMRunnerConfiguration [JUnit]
null
resolved fixed
f999754
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-05T18:20:19Z
2003-11-04T23:53:20Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitBaseLaunchConfiguration.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.junit.launcher; import java.io.File; import java.text.MessageFormat; import java.util.HashSet; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; 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.internal.junit.ui.JUnitMessages; import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; import org.eclipse.jdt.internal.junit.util.TestSearchEngine; import org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate; import org.eclipse.jdt.launching.ExecutionArguments; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.IVMRunner; import org.eclipse.jdt.launching.SocketUtil; import org.eclipse.jdt.launching.VMRunnerConfiguration; /** * Abstract launch configuration delegate for a JUnit test. */ public abstract class JUnitBaseLaunchConfiguration extends AbstractJavaLaunchConfigurationDelegate { public static final String PORT_ATTR= JUnitPlugin.PLUGIN_ID+".PORT"; //$NON-NLS-1$ public static final String TESTTYPE_ATTR= JUnitPlugin.PLUGIN_ID+".TESTTYPE"; //$NON-NLS-1$ public static final String TESTNAME_ATTR= JUnitPlugin.PLUGIN_ID+".TESTNAME"; //$NON-NLS-1$ public static final String ATTR_KEEPRUNNING = JUnitPlugin.PLUGIN_ID+ ".KEEPRUNNING_ATTR"; //$NON-NLS-1$ public static final String LAUNCH_CONTAINER_ATTR= JUnitPlugin.PLUGIN_ID+".CONTAINER"; //$NON-NLS-1$ /** * @see ILaunchConfigurationDelegate#launch(ILaunchConfiguration, String) */ public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor pm) throws CoreException { IJavaProject javaProject= getJavaProject(configuration); if ((javaProject == null) || !javaProject.exists()) { abort(JUnitMessages.getString("JUnitBaseLaunchConfiguration.error.invalidproject"), null, IJavaLaunchConfigurationConstants.ERR_NOT_A_JAVA_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$ } IType[] testTypes = getTestTypes(configuration, javaProject, pm); if (testTypes.length == 0) { abort(JUnitMessages.getString("JUnitBaseLaunchConfiguration.error.notests"), null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$ } IVMInstall install= getVMInstall(configuration); IVMRunner runner = install.getVMRunner(mode); if (runner == null) { abort(MessageFormat.format(JUnitMessages.getString("JUnitBaseLaunchConfiguration.error.novmrunner"), new String[]{install.getId()}), null, IJavaLaunchConfigurationConstants.ERR_VM_RUNNER_DOES_NOT_EXIST); //$NON-NLS-1$ } int port= SocketUtil.findUnusedLocalPort("", 5000, 15000); //$NON-NLS-1$ VMRunnerConfiguration runConfig= launchTypes(configuration, mode, testTypes, port); setDefaultSourceLocator(launch, configuration); launch.setAttribute(PORT_ATTR, Integer.toString(port)); launch.setAttribute(TESTTYPE_ATTR, testTypes[0].getHandleIdentifier()); runner.run(runConfig, launch, pm); } protected VMRunnerConfiguration launchTypes(ILaunchConfiguration configuration, String mode, IType[] tests, int port) throws CoreException { File workingDir = verifyWorkingDirectory(configuration); String workingDirName = null; if (workingDir != null) workingDirName = workingDir.getAbsolutePath(); // Program & VM args String vmArgs= getVMArguments(configuration); ExecutionArguments execArgs = new ExecutionArguments(vmArgs, ""); //$NON-NLS-1$ VMRunnerConfiguration runConfig= createVMRunner(configuration, tests, port, mode); runConfig.setVMArguments(execArgs.getVMArgumentsArray()); runConfig.setWorkingDirectory(workingDirName); String[] bootpath = getBootpath(configuration); runConfig.setBootClassPath(bootpath); return runConfig; } public IType[] getTestTypes(ILaunchConfiguration configuration, IJavaProject javaProject, IProgressMonitor pm) throws CoreException { String testTypeName = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)null); if (pm == null) pm= new NullProgressMonitor(); // if ((testTypeName == null) || (testTypeName.trim().length() < 1)) { // abort("No test type specified", null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$ // } String containerHandle = configuration.getAttribute(LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$ if (containerHandle.length() == 0) { return findSingleTest(javaProject, testTypeName); } else return findTestsInContainer(javaProject, containerHandle, pm); } /** * @inheritdoc * @param javaProject * @param containerHandle * @param pm * @return */ private IType[] findTestsInContainer(IJavaProject javaProject, String containerHandle, IProgressMonitor pm) { IJavaElement container= JavaCore.create(containerHandle); Set result= new HashSet(); try { TestSearchEngine.doFindTests(new Object[]{container}, result, pm); } catch (InterruptedException e) { } return (IType[]) result.toArray(new IType[result.size()]) ; } public IType[] findSingleTest(IJavaProject javaProject, String testName) throws CoreException { IType type = null; try { type = findType(javaProject, testName); } catch (JavaModelException jme) { abort("Test type does not exist", null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$ } if (type == null) { abort("Test type does not exist", null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$ } return new IType[]{type}; } /** * Throws a core exception with the given message and optional * exception. The exception's status code will indicate an error. * * @param message error message * @param exception cause of the error, or <code>null</code> * @exception CoreException with the given message and underlying * exception */ protected void abort(String message, Throwable exception, int code) throws CoreException { throw new CoreException(new Status(IStatus.ERROR, JUnitPlugin.PLUGIN_ID, code, message, exception)); } /** * Find the specified (fully-qualified) type name in the specified java project. */ private IType findType(IJavaProject javaProject, String mainTypeName) throws JavaModelException { return javaProject.findType(mainTypeName); } /** * Override to create a custom VMRunnerConfiguration for a launch configuration. */ protected abstract VMRunnerConfiguration createVMRunner(ILaunchConfiguration configuration, IType[] testTypes, int port, String runMode) throws CoreException; protected boolean keepAlive(ILaunchConfiguration config) { try { return config.getAttribute(ATTR_KEEPRUNNING, false); } catch(CoreException e) { } return false; } }
46,227
Bug 46227 MarkerResolution extension point broken?
20031106 With the RCP change, the extension point org.eclipse.ui.ide.markerResolution seems to be broken. IDE.getMarkerHelpRegistry().getResolutions does not return anything.
resolved fixed
5f8c568
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-06T19:10:31Z
2003-11-06T20:20:00Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/MarkerResolutionTest.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation 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.tests.quickfix; import java.util.Arrays; import java.util.Hashtable; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.ui.IEditorPart; 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.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor; public class MarkerResolutionTest extends QuickFixTest { private static final Class THIS= MarkerResolutionTest.class; private IJavaProject fJProject1; private IPackageFragmentRoot fSourceFolder; public MarkerResolutionTest(String name) { super(name); } public static Test allTests() { return new ProjectTestSetup(new TestSuite(THIS)); } public static Test suite() { if (true) { return allTests(); } else { TestSuite suite= new TestSuite(); suite.addTest(new MarkerResolutionTest("testQuickFixAfterModification")); 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"); JavaCore.setOptions(options); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); fJProject1= ProjectTestSetup.getProject(); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); } protected void tearDown() throws Exception { JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath()); } private IMarker createMarker(ICompilationUnit cu, int line, int offset, int len) throws CoreException { IFile file= (IFile) cu.getResource(); IMarker marker= file.createMarker("org.eclipse.jdt.ui.tests.testmarker"); marker.setAttribute(IMarker.LOCATION, cu.getElementName()); marker.setAttribute(IMarker.MESSAGE, "Test marker"); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LINE_NUMBER, line); marker.setAttribute(IMarker.CHAR_START, offset); marker.setAttribute(IMarker.CHAR_END, offset + len); return marker; } public void testQuickFix() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" void foo(Vector vec) {\n"); buf.append(" goo(true);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); createMarker(cu, 0, 0, 7); IEditorPart part= EditorUtility.openInEditor(cu); ITextViewer viewer= ((JavaEditor) part).getViewer(); try { JavaCorrectionAssistant assistant= new JavaCorrectionAssistant(part); JavaCorrectionProcessor processor= new JavaCorrectionProcessor(assistant); ICompletionProposal[] proposals= processor.computeCompletionProposals(viewer, 0); assertNumberOf("proposals", proposals.length, 1); assertCorrectLabels(Arrays.asList(proposals)); IDocument doc= JavaUI.getDocumentProvider().getDocument(part.getEditorInput()); proposals[0].apply(doc); buf= new StringBuffer(); buf.append("PACKAGE test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" void foo(Vector vec) {\n"); buf.append(" goo(true);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(doc.get(), buf.toString()); } finally { JavaPlugin.getActivePage().closeAllEditors(false); } } public void testQuickFixAfterModification() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" void foo(Vector vec) {\n"); buf.append(" goo(true);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int markerPos= 8; createMarker(cu, 0, markerPos, 5); IEditorPart part= EditorUtility.openInEditor(cu); try { IDocument doc= JavaUI.getDocumentProvider().getDocument(part.getEditorInput()); doc.replace(0, 0, "\n"); // insert new line JavaCorrectionAssistant assistant= new JavaCorrectionAssistant(part); JavaCorrectionProcessor processor= new JavaCorrectionProcessor(assistant); ICompletionProposal[] proposals= processor.computeCompletionProposals(null, markerPos + 1); assertNumberOf("proposals", proposals.length, 1); assertCorrectLabels(Arrays.asList(proposals)); proposals[0].apply(doc); buf= new StringBuffer(); buf.append("\n"); buf.append("package TEST1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" void foo(Vector vec) {\n"); buf.append(" goo(true);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(doc.get(), buf.toString()); } finally { JavaPlugin.getActivePage().closeAllEditors(false); } } }
45,193
Bug 45193 hierarchy scope search only shows types that exist in jars
null
resolved fixed
d8467af
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-13T10:03:26Z
2003-10-20T08:53:20Z
org.eclipse.jdt.ui/core
45,193
Bug 45193 hierarchy scope search only shows types that exist in jars
null
resolved fixed
d8467af
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-13T10:03:26Z
2003-10-20T08:53:20Z
extension/org/eclipse/jdt/internal/corext/util/IFileTypeInfo.java
46,329
Bug 46329 PasteActionTest#test2 failts
N20031109 After converting to RCP the above test started to fail
resolved fixed
997ac85
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-13T15:25:41Z
2003-11-09T20:33:20Z
org.eclipse.jdt.ui.tests.refactoring/test
46,329
Bug 46329 PasteActionTest#test2 failts
N20031109 After converting to RCP the above test started to fail
resolved fixed
997ac85
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-13T15:25:41Z
2003-11-09T20:33:20Z
cases/org/eclipse/jdt/ui/tests/reorg/PasteActionTest.java
46,329
Bug 46329 PasteActionTest#test2 failts
N20031109 After converting to RCP the above test started to fail
resolved fixed
997ac85
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-13T15:25:41Z
2003-11-09T20:33:20Z
org.eclipse.jdt.ui/core
46,329
Bug 46329 PasteActionTest#test2 failts
N20031109 After converting to RCP the above test started to fail
resolved fixed
997ac85
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-13T15:25:41Z
2003-11-09T20:33:20Z
extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java
46,329
Bug 46329 PasteActionTest#test2 failts
N20031109 After converting to RCP the above test started to fail
resolved fixed
997ac85
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-13T15:25:41Z
2003-11-09T20:33:20Z
org.eclipse.jdt.ui/core